Exemplo n.º 1
0
int SemGetValue( sem_t *pSem, int *value )
{
	return sem_getvalue( pSem, value );
}
Exemplo n.º 2
0
ssize_t pipecommon_write(FAR struct file *filep, FAR const char *buffer,
                         size_t len)
{
  FAR struct inode      *inode    = filep->f_inode;
  FAR struct pipe_dev_s *dev      = inode->i_private;
  ssize_t            nwritten = 0;
  ssize_t            last;
  int                nxtwrndx;
  int                sval;

  DEBUGASSERT(dev);
  pipe_dumpbuffer("To PIPE:", (FAR uint8_t *)buffer, len);

  if (len == 0)
    {
      return 0;
    }

  /* At present, this method cannot be called from interrupt handlers.  That is
   * because it calls sem_wait (via pipecommon_semtake below) and sem_wait cannot
   * be called from interrupt level.  This actually happens fairly commonly
   * IF dbg() is called from interrupt handlers and stdout is being redirected
   * via a pipe.  In that case, the debug output will try to go out the pipe
   * (interrupt handlers should use the lldbg() APIs).
   *
   * On the other hand, it would be very valuable to be able to feed the pipe
   * from an interrupt handler!  TODO:  Consider disabling interrupts instead
   * of taking semaphores so that pipes can be written from interrupt handlers
   */

  DEBUGASSERT(up_interrupt_context() == false);

  /* Make sure that we have exclusive access to the device structure */

  if (sem_wait(&dev->d_bfsem) < 0)
    {
      return ERROR;
    }

  /* Loop until all of the bytes have been written */

  last = 0;
  for (;;)
    {
      /* Calculate the write index AFTER the next byte is written */

      nxtwrndx = dev->d_wrndx + 1;
      if (nxtwrndx >= CONFIG_DEV_PIPE_SIZE)
        {
          nxtwrndx = 0;
        }

      /* Would the next write overflow the circular buffer? */

      if (nxtwrndx != dev->d_rdndx)
        {
          /* No... copy the byte */

          dev->d_buffer[dev->d_wrndx] = *buffer++;
          dev->d_wrndx = nxtwrndx;

          /* Is the write complete? */

          nwritten++;
          if ((size_t)nwritten >= len)
            {
              /* Yes.. Notify all of the waiting readers that more data is available */

              while (sem_getvalue(&dev->d_rdsem, &sval) == 0 && sval < 0)
                {
                  sem_post(&dev->d_rdsem);
                }

              /* Notify all poll/select waiters that they can write to the FIFO */

              pipecommon_pollnotify(dev, POLLIN);

              /* Return the number of bytes written */

              sem_post(&dev->d_bfsem);
              return len;
            }
        }
      else
        {
          /* There is not enough room for the next byte.  Was anything written in this pass? */

          if (last < nwritten)
            {
              /* Yes.. Notify all of the waiting readers that more data is available */

              while (sem_getvalue(&dev->d_rdsem, &sval) == 0 && sval < 0)
                {
                  sem_post(&dev->d_rdsem);
                }
            }
          last = nwritten;

          /* If O_NONBLOCK was set, then return partial bytes written or EGAIN */

          if (filep->f_oflags & O_NONBLOCK)
            {
              if (nwritten == 0)
                {
                  nwritten = -EAGAIN;
                }
              sem_post(&dev->d_bfsem);
              return nwritten;
            }

          /* There is more to be written.. wait for data to be removed from the pipe */

          sched_lock();
          sem_post(&dev->d_bfsem);
          pipecommon_semtake(&dev->d_wrsem);
          sched_unlock();
          pipecommon_semtake(&dev->d_bfsem);
        }
    }
}
Exemplo n.º 3
0
  /**
   * The method reads all sensors. It also detects if the chest button was pressed
   * for at least three seconds. In that case, it shuts down the robot.
   */
  void readSensors()
  {
    // get new sensor values and copy them to the shared memory block
    try
    {
      // copy sensor values into the shared memory block
      int writingSensors = 0;
      if(writingSensors == data->newestSensors)
        ++writingSensors;
      if(writingSensors == data->readingSensors)
        if(++writingSensors == data->newestSensors)
          ++writingSensors;
      assert(writingSensors != data->newestSensors);
      assert(writingSensors != data->readingSensors);

      float* sensors = data->sensors[writingSensors];
      for(int i = 0; i < lbhNumOfSensorIds; ++i)
        sensors[i] = *sensorPtrs[i];

      AL::ALValue value = memory->getData("GameCtrl/RoboCupGameControlData");
      if(value.isBinary() && value.getSize() == sizeof(RoboCup::RoboCupGameControlData))
        memcpy(&data->gameControlData[writingSensors], value, sizeof(RoboCup::RoboCupGameControlData));

      data->newestSensors = writingSensors;

      // detect shutdown request via chest-button
      if(*sensorPtrs[chestButtonSensor] == 0.f)
        startPressedTime = dcmTime;
      else if(state != shuttingDown && startPressedTime && dcmTime - startPressedTime > 3000)
      {
        if(*sensorPtrs[rBumperRightSensor] != 0.f || *sensorPtrs[rBumperLeftSensor] != 0.f ||
           *sensorPtrs[lBumperRightSensor] != 0.f || *sensorPtrs[lBumperLeftSensor] != 0.f)
          (void) !system("( /home/nao/bin/bhumand stop && sudo shutdown -r now ) &");
        else
          (void) !system("( /home/nao/bin/bhumand stop && sudo shutdown -h now ) &");
        state = preShuttingDown;
      }
    }
    catch(AL::ALError& e)
    {
      fprintf(stderr, "libbhuman: %s\n", e.toString().c_str());
    }

    // raise the semaphore
    if(sem != SEM_FAILED)
    {
      int sval;
      if(sem_getvalue(sem, &sval) == 0)
      {
        if(sval < 1)
        {
          sem_post(sem);
          frameDrops = 0;
        }
        else
        {
          if(frameDrops == 0)
            fprintf(stderr, "libbhuman: dropped sensor data.\n");
          ++frameDrops;
        }
      }
    }
  }
Exemplo n.º 4
0
/*===================================================================*/
BOOL InfoNES_CreateContext(JNIEnv *pEnv,
						NES_CONTEXT *pNesContext,
						jobject refNesSimu,
						jobject refBitmap)
{
	if( 0 == pEnv || 0 == pNesContext )
	{
		LOGV("InfoNES_CreateContext failed 1");
		return 0;
	}
	// Caches JavaVM.
	if( ( 0 == pNesContext->pJavaVM )
		&& ((*pEnv)->GetJavaVM(pEnv, &(pNesContext->pJavaVM)) != JNI_OK) )
	{
		LOGV("InfoNES_CreateContext failed 2");
		return 0;
	}
	// caches classNesSimu
	if( 0 == pNesContext->classNesSimu )
	{
		jclass clsNesSimu = (*pEnv)->FindClass(pEnv, "com/falcon/nesSimon/NesSimu");
		LOGV("InfoNES_CreateContext\n");
		pNesContext->classNesSimu = makeGlobalRef(pEnv, clsNesSimu);
		if( 0 == pNesContext->classNesSimu )
		{
			LOGV("InfoNES_CreateContext failed 3");
			return 0;
		}
	}
	if( 0 != refNesSimu && (JNI_TRUE != (*pEnv)->IsSameObject(pEnv, pNesContext->objNesSimu, refNesSimu )))
	{
		pNesContext->objNesSimu = makeGlobalRef(pEnv, refNesSimu);
		if( 0 == pNesContext->objNesSimu )
		{
			LOGV("InfoNES_CreateContext failed 4");
			return 0;
		}
	}
	if( 0 != refBitmap && (JNI_TRUE != (*pEnv)->IsSameObject(pEnv, pNesContext->objBitmap, refBitmap )))
	{
		pNesContext->objBitmap = makeGlobalRef(pEnv, refBitmap);
		if( 0 == pNesContext->objBitmap )
		{
			LOGV("InfoNES_CreateContext failed 5");
			return 0;
		}
	}
	if( 0 == pNesContext->methodUpdateView )
	{
		pNesContext->methodUpdateView = (*pEnv)->GetMethodID(pEnv, pNesContext->classNesSimu, "UpdateView", "()V");
		if( 0 == pNesContext->methodUpdateView )
		{
			LOGV("InfoNES_CreateContext failed 6");
			return 0;
		}
	}
	NES_MUTEX_CREATE( WaitFlagCriticalSection );
	NES_MUTEX_CREATE( PauseFlagCriticalSection );
	NES_SEM_INIT(pNesContext->sem, 0);
	{
		int sem_val;
		sem_getvalue(&(pNesContext->sem), &sem_val);
		LOGV("InfoNES_CreateContext success, sem = %d", sem_val);
	}
	return 1;
}
Exemplo n.º 5
0
int pipecommon_close(FAR struct file *filep)
{
  FAR struct inode      *inode = filep->f_inode;
  FAR struct pipe_dev_s *dev   = inode->i_private;
  int                sval;

  DEBUGASSERT(dev && dev->d_refs > 0);

  /* Make sure that we have exclusive access to the device structure.
   * NOTE: close() is supposed to return EINTR if interrupted, however
   * I've never seen anyone check that.
   */

  pipecommon_semtake(&dev->d_bfsem);

  /* Decrement the number of references on the pipe.  Check if there are
   * still outstanding references to the pipe.
   */

  /* Check if the decremented reference count would go to zero */

  if (--dev->d_refs > 0)
    {
      /* No more references.. If opened for writing, decrement the count of
       * writers on the pipe instance.
       */

      if ((filep->f_oflags & O_WROK) != 0)
        {
          /* If there are no longer any writers on the pipe, then notify all of the
           * waiting readers that they must return end-of-file.
           */

          if (--dev->d_nwriters <= 0)
            {
              while (sem_getvalue(&dev->d_rdsem, &sval) == 0 && sval < 0)
                {
                  sem_post(&dev->d_rdsem);
                }

              /* Inform poll readers that other end closed. */

              pipecommon_pollnotify(dev, POLLHUP);
            }
        }

      /* If opened for reading, decrement the count of readers on the pipe
       * instance.
       */

      if ((filep->f_oflags & O_RDOK) != 0)
        {
          if (--dev->d_nreaders <= 0)
            {
              if (PIPE_IS_POLICY_0(dev->d_flags))
                {
                  /* Inform poll writers that other end closed. */

                  pipecommon_pollnotify(dev, POLLERR);
                }
            }
        }
    }

  /* What is the buffer management policy?  Do we free the buffer when the
   * last client closes the pipe policy 0, or when the buffer becomes empty.
   * In the latter case, the buffer data will remain valid and can be
   * obtained when the pipe is re-opened.
   */

  else if (PIPE_IS_POLICY_0(dev->d_flags) || dev->d_wrndx == dev->d_rdndx)
    {
      /* Policy 0 or the buffer is empty ... deallocate the buffer now. */

      kmm_free(dev->d_buffer);
      dev->d_buffer = NULL;

      /* And reset all counts and indices */

      dev->d_wrndx    = 0;
      dev->d_rdndx    = 0;
      dev->d_refs     = 0;
      dev->d_nwriters = 0;
      dev->d_nreaders = 0;

#ifndef CONFIG_DISABLE_PSEUDOFS_OPERATIONS
      /* If, in addition, we have been unlinked, then also need to free the
       * device structure as well to prevent a memory leak.
       */

      if (PIPE_IS_UNLINKED(dev->d_flags))
        {
          pipecommon_freedev(dev);
          return OK;
        }
#endif
   }

  sem_post(&dev->d_bfsem);
  return OK;
}
Exemplo n.º 6
0
Arquivo: p.c Projeto: ryane22/CS451
int main(int argc, char *argv[]) {
	sem_t *semaphore;
	semaphore = sem_open("/RESEMAPHORE", O_CREAT);
	sem_t *shared;
	shared = sem_open("/RESHARED", O_CREAT);
	
	int semval;
	int shareval;
	
	while(1) {
		sem_getvalue(semaphore, &semval);
		//printf("SEMVAL is %d in %s\n", semval, argv[0]);
		if (semval > 1) {
			//printf("Child killed\n");
			exit(0);
		}
		else if (semval == 1) {
			sem_wait(semaphore);
			sem_getvalue(semaphore, &semval);
			//printf(">>locking  new semval %d  in %s\n", semval, argv[0]);
			
			//printf("BEGIN %s\n", argv[0]);
			//gets the id and the file name
			char arg[42];
			strcpy(arg, argv[0]);
			
			char buf[4] = "";
			int i;
			for (i=0; i<1; i++) {
				sprintf(buf, "%s%c", buf, arg[i]);
			}
			char name[4];
			strcpy(name, buf);
			//printf("name %s", name);
			
			char buf2[42] = "";
			for (++i; i<sizeof(arg); i++) {
				if (arg[i] == '\0')
					break;
				sprintf(buf2, "%s%c", buf2, arg[i]);
			}
			char file[40];
			strcpy(file, buf2);
			//printf("file %s\n", file);
			
			//jump to shared
			int semval;
			sem_getvalue(shared, &semval);
			//printf("semval from child is %d\n", semval);
			FILE *dFile;
			dFile = fopen(file, "r");
			int seek;
			for (seek = 0; seek<semval; seek++)
				fgetc(dFile);
			
			//create a random number of chacters [1-10] to read from a file
			srand(atoi(name));
			int numChar = (rand()%10)+1;
			//printf("\nnumChar is %d\n\n", numChar);
			
			//for loop to sem_post that many times
			int j;
			for (j=0; j<numChar; j++)
				sem_post(shared);
			
			//read from file n number of characters
			char fileBuf[14] = "";
			sprintf(fileBuf, "_p%s", name);                          //add this back later
			int k;
			for (k=0; k<numChar; k++) {
				char c = fgetc(dFile);
				if (c == EOF)
					sprintf(fileBuf, "%s`", fileBuf);
				else
					sprintf(fileBuf, "%s%c", fileBuf, c);
			}
			fclose(dFile);
			
			//write to pipe
			int pipe;
			pipe = open("REPIPE", O_WRONLY);
			write(pipe, fileBuf, sizeof(fileBuf));
			close(pipe);
			//usleep(500);
		}
	}
}
Exemplo n.º 7
0
int sys_sem(struct semaphore_s **sem, uint_t operation, uint_t pshared, int *value)
{
	kmem_req_t req;
	struct semaphore_s *isem;
	struct task_s *task;
	error_t err = EINVAL;
	int val;

	task = current_task;

	if((err = vmm_check_address("usr sem ptr", task, sem, sizeof(struct semaphore_s*))))
		goto SYS_SEM_END;

	if((err = cpu_copy_from_uspace(&isem, sem, sizeof(struct semaphore_s *))))
		goto SYS_SEM_END;
  
	switch(operation)
	{
	case SEM_INIT:
		if((err = vmm_check_address("usr sem op", task, value, sizeof(int*))))
			break;
    
		if((err = cpu_copy_from_uspace(&val, value, sizeof(int*))))
			break;

		req.type  = KMEM_SEM;
		req.size  = sizeof(*isem);
		req.flags = AF_USER;

		if((isem = kmem_alloc(&req)) == NULL)
		{
			err = ENOMEM;
			break;
		}
    
		if((err = sem_init(isem, val, SEM_SCOPE_USR)))
			break;
    
		if((err = cpu_copy_to_uspace(sem,&isem,sizeof(struct semaphore_s*))))
		{
			req.ptr = isem;
			kmem_free(&req);
			break;
		}
		return 0;

	case SEM_GETVALUE:
		if(isBadSem(isem))
			break;
    
		if((err = vmm_check_address("usr sem val", task, value, sizeof(int*))))
			break;

		if((err = sem_getvalue(isem, &val)))
			break;

		if((err = cpu_copy_to_uspace(value, &val, sizeof(int))))
			break;
    
		return 0;
    
	case SEM_WAIT:
		if(isBadSem(isem))
			break;
    
		if((err = sem_wait(isem)))
			break;

		return 0;

	case SEM_TRYWAIT:
		if(isBadSem(isem))
			break;
    
		return sem_trywait(isem);

	case SEM_POST:
		if(isBadSem(isem))
			break;
    
		if((err=sem_post(isem)))
			break;

		return 0;

	case SEM_DESTROY:
		if(isBadSem(isem))
			break;
    
		if((err = sem_destroy(isem)))
			break;
    
		req.type = KMEM_SEM;
		req.ptr  = isem;
		kmem_free(&req);
		return 0;
    
	default:
		err = EINVAL;
	}

SYS_SEM_END:
	current_thread->info.errno = err;
	return -1;
}
Exemplo n.º 8
0
int flx_semaphore_t::get(){ int x; sem_getvalue(&sem,&x); return x; }
Exemplo n.º 9
0
int sipc_semaphore_get_value(int id) {
  int val;
  sem_getvalue(semaphore[id], &val);
  return val;
}
Exemplo n.º 10
0
int qSem::Query()
{
	int value;
	if (sem_getvalue(&sem, &value) != 0) value = -1;
	return(value);
}
Exemplo n.º 11
0
Arquivo: inc.c Projeto: junk2112/os2
int main (int arc, char ** argv, char **envp) 
{
  char temp[16];
  int fd;
  //system("rm test.txt");
  if ( (fd = open("./test.txt", O_RDWR|O_CREAT)) == -1)
  {
    printf("open file error\n");
    return 1;  
  }
  write(fd, "0\0", 2);
  close(fd);
  
  sem_t * sr;
  if ( (sr = sem_open ("/_semName_", O_RDWR|O_CREAT, 0666, 1)) == SEM_FAILED)
  {
   printf("sem_open error\n");
   return 1;
  }
  int currentValue;
  sem_getvalue(sr,&currentValue);
  printf("current value of sem is %d\n", currentValue);
  
  int pid;
  if ( (pid = fork()) == -1)
  {
    printf("fork error\n");
    return 1;
  }
  else 
    if (pid == 0)//child
    {
      char temp[16];
      int fd,i;
      for (i=0; i<n; ++i)
      {
		//int value;
		//sem_getvalue(sr, &value);
		//printf("child before: sem value is %d\n",value);
		sem_wait(sr);
		//sem_getvalue(sr, &value);
		//printf("child after: sem value is %d\n",value);
		
		if ( (fd = open("./test.txt", O_RDWR|O_CREAT)) == -1)
		{
		  printf("open error\n");
		  return 1;
		}
		read(fd, &temp, 16);
		int number = atoi(temp);
		number++;
		lseek(fd, 0, SEEK_SET);
		sprintf(temp, "%d", number);
		printf("child`s value is %s\n", temp);
		write(fd, &temp, strlen(temp));
		write(fd, "\0", 1);
		close(fd);
		sem_post(sr);
      }
    } 
    else//parent
    {
      char temp[16];
      int fd,i;
      for (i=0; i<n; ++i)
      {
		//int value;
		//sem_getvalue(sr, &value);
		//printf("parent before: sem value is %d\n",value);	
		sem_wait(sr);
		//sem_getvalue(sr, &value);
		//printf("parent after: sem value is %d\n",value);
		
		if ( (fd = open("./test.txt", O_RDWR|O_CREAT)) == -1)
		{
		  printf("open error\n");
		  return 1;
		}
		read(fd, &temp, 16);
		int number = atoi(temp);
		number++;
		lseek(fd, 0, SEEK_SET);
		sprintf(temp, "%d", number);
		printf("parent`s temp is %s\n", temp);
		write(fd, &temp, strlen(temp));
		write(fd, "\0", 1);
		close(fd);
		sem_post(sr);
      } 
      sem_unlink("/_semName_");
    }
	return 0;
}
Exemplo n.º 12
0
main(){

int  shared, i;
int *buffer, *value;

  	value = (int*) malloc(sizeof(int));
  	
  		/*Apertura de los semáforos*/
  	
  		/*Dado que el consumidor ha de ser lanzado después del productor, los semáforos ya habrán sido creados e inicializados, por lo que el consumidor 
  		sólo debe abrilos pero sin inicializarlos.*/
	
		srand(time(NULL));
		
		/*EMPTY se inicializa con valor N, y se irá decrementando su valor a medida que el productor introduzca elementos en el mismo. En caso de que 
		se llene el buffer, tomará valor 0, y el productor se bloqueará. Del mismo modo, cada vez que el consumidor consuma un elemento, incrementará su
		valor para que el productor pueda seguir produciendo.*/
		if ((empty = sem_open ("EMPTY", N)) == SEM_FAILED){
			perror("Error en la creación de EMPTY\n");
		}
		
		/*FULL se inicializa con valor 0, y se irá incrementando su valor a medida que el productor introduzca elementos en el mismo. Del mismo modo,
		cada vez que el consumidor consuma un elemento, decrementará su valor. En caso de que se vacíe el buffer, tomará valor 0, por lo que el consumidor
		se bloqueará en espera de que el productor produzca un elemento.*/
		if ((full = sem_open ("FULL", 0)) == SEM_FAILED){
			perror("Error en la creación de FULL\n");
		}
		/*MUTEX está pensado para garantizar exclusión mutua, de modo que para que un proceso pueda acceder a la región crítica, este semáforo ha de tener 
		valor 1, y hacerse un down del mismo, para impedir que otro proceso acceda al mismo tiempo. Al salir de la región crítica, se realizará un up
		del mismo para desbloquear a aquellos procesos que estuviesen esperando para entrar.*/
		if ((mutex = sem_open ("MUTEX", 1)) == SEM_FAILED){
			perror("Error en la creación de MUTEX\n");
		}
		
		/*****************************************************************/
		
		/*Apertura de la zona de memoria compartida*/
		
		/*Al igual que sucede con los semáforos, es el primer productor que se lanza quien crea el área de memoria compartida, de modo que los
		consumidores sólo tienen que abrirla y proyectarla en memoria. Dado que el consumidor no escribe en dicha área, deberá abrir el archivo
		con permisos de sólo lectura, y realizará la proyección con protección de escritura y mapeado compartido.*/
		
		shared = open ("buffer", O_RDONLY);
		if (shared == -1){
			perror ("Error en el open\n");
			exit(1);
		}
		buffer = (int*) mmap(NULL, N*sizeof(int), PROT_READ, MAP_SHARED, shared, 0);
		if (*buffer == -1){
			perror("Error en la función mmap\n");
			exit(1);
		}
		
		/*****************************************************************/
		
		/*Lectura del buffer*/
		
		/*Para asegurarnos de que los semáforos serán cerrados y deslinkados al final de la ejecución del programa, debemos asegurar que el consumidor
		entre en el bucle de consumo un número finito de veces pues, en caso contrario, deberíamos abortar manualmente la ejecución del programa y no
		permituiríamos la ejecución íntegra del código. Esto generaría un problema ya que, al no deslinkar los semáforos al comienzo del productor, 
		por los motivos descritos en el código del mismo, cuando el productor los quisiese crear éstos ya existiesen en el kernel y no se les asignase
		el valor deseado, como se explica también en el código del productor.
		
		Para poder acceder a la región crítica, debe de existir algún elemento en el buffer (full > 0), y se debe garantizar la exclusión mutua 
		(mutex > 0). En caso de que no se cumpla uno de estos requisitos, el proceso se bloqueará esperando a ser desbloqueado por un productor.
		Después de haber consumido un elemento en la posición del buffer igual al valor de FULL, el consumidor hará un up de mutex, para desbloquear 
		a aquellos procesos que deseasen entrar a la región crítica, y un up de EMPTY, para desbloquar a aquellos procesos que estuviesen esperando para 
		entrar en la región crítica, de haberlos, y para indicar que se ha consumido un elemento del buffer, según el planteamiento de los 
		semáforos, explicado al inicio.*/
		
		for (i = 0; i < 10*N;i++){
			sem_wait(full);
			sem_wait(mutex);
			sem_getvalue(full, value);
			printf("El consumidor ha sacado el valor %d de la posición %d\n", i, *value);
			fflush(stdout);
			sleep(rand()%5);
			sem_post(mutex);
			sem_post(empty);
		}
		
		/*****************************************************************/
		
		printf("Fin del consumo\n");
		
		/*Cierre de la proyección, el archivo y los semáforos*/
		
		munmap(buffer, N*sizeof(int));
		close(shared);
		sem_close(empty);
		sem_close(full);
		sem_close(mutex);
		
		/*****************************************************************/
		
	return (0);
}
Exemplo n.º 13
0
int main( int argc, char *argv[] ) {
  printf( "beta\n" );

  if( argc != 4 ) { // to change when adding priority, nice, algorithm, etc.
    printf( "usage: beta <led#> <freq(secs)> <loadcount>\n" );
    return EXIT_FAILURE;
  }

  // register the handler
  struct sigaction sa;
    zero( sa );
    sa.sa_handler = handler; // void (*sa_handler)(int);
  sigaction( SIGINT, &sa, NULL );
  
  //   initialize the semaphor
  // sem_t sem;
  // sem_init( &sem, 0, 0 );
  if( sem_init( &sem, 0, 0 ) ) {
    printf( "error initializing sem\n" );
    return EXIT_FAILURE;
  }
  // sem_post( &sem ); // up
  // sem_wait( &sem ); // down
  // sem_getvalue( &sem, &int );
  // sem_destroy( &sem );
  
  
  // open led file
  char ss[ 0xff ];
  int state = 1; // led_state
  sprintf( ss, "/sys/class/leds/beaglebone::usr%s/brightness", argv[ 1 ] );
  FILE *led;
  led = fopen( ss, "w" );
  if( !led ) {
    printf( "couldn't open %s", ss );
    return EXIT_SUCCESS;
  }
  
  
  // create timer
  clockid_t cid = CLOCK_MONOTONIC;
  struct sigevent se;
    zero( se );
    se.sigev_notify = SIGEV_SIGNAL;
    se.sigev_signo = SIGINT;
  timer_t tid;
  if( timer_create( cid, &se, &tid ) ) {
    printf( "couldn't create timer\n" );
    return EXIT_FAILURE;
  }
  // & arm it
  struct itimerspec its;
    zero( its );
    its.it_value.tv_nsec = 2; // effectively immediate
    // its.it_interval.tv_sec = 1; // every second
    // its.it_interval.tv_nsec = 100000000;
    // int freq = atoi( argv[ 2 ] );
    float freq;
    sscanf( argv[ 2 ], "%f", &freq );
    its.it_interval.tv_sec = floor( freq );
    its.it_interval.tv_nsec =  ( freq - its.it_interval.tv_sec ) * 100000000;
  timer_settime( tid, 0, &its, NULL );
  
  
  volatile int counter;
  int i = 0, load;
  load = atoi( argv[ 3 ] );
  forever {
    sem_getvalue( &sem, &i );
    if( i > 1 ) {
      printf( "sem_value: %i\n", i );
      if( i > 16 ) {
        printf( "cpu overloaded: exiting\n" );
        return EXIT_SUCCESS;
      }
    }
    while( sem_wait( &sem ) ); // hack

    // printf( "tick, state:%i\n", state );
    for( counter = 0; counter < load; counter++ ); // 'load' loop
    if( state )
      fwrite( "0", sizeof( char ), strlen( "0" ), led );
    else
      fwrite( "1", sizeof( char ), strlen( "1" ), led );
    fflush( led );
    state = state ^ 1;
  }
  
  
  // never reached
  fclose( led );
  return 0;
}
Exemplo n.º 14
0
int main(int argc, char** argv)
{
	int fd1,fd2;

	int* ptr1;
	int* ptr2;
	int flag = PROT_WRITE | PROT_READ;
    int semVal;
	int userguessNum;

	sem_t* startSem = sem_open("startSem", 0);
    sem_t* clientNum = sem_open("clientNum", 0);
    sem_t* waitInputSem = sem_open("waitInputSem", 0);
    sem_t* waitOutputSem = sem_open("waitOutputSem", 0);
    sem_t* doOneClient = sem_open("doOneClient", 0);
    sem_t* nowStartGameSem = sem_open("nowStartGameSem", 0);
    sem_t* waitPrintSem = sem_open("waitPrintSem", 0);
    sem_t* notEnterSem = sem_open("notEnterSem", 0);

    if((fd1 = open("input.mm", O_RDWR, 0666)) < 0) {
	    perror("File open error");
	    exit(1);
	}

	if((ptr1 = (int *)mmap(0, 4096, flag, MAP_SHARED, fd1 ,0)) == NULL) {
	    perror("mmap error");
	    exit(1);
	}

	if((fd2 = open("output.mm", O_RDWR, 0666)) < 0) {
	    perror("File open error");
	    exit(1);
	}

	if((ptr2 = (int *)mmap(0, 4096, flag, MAP_SHARED, fd2 ,0)) == NULL) {
	    perror("mmap error");
	    exit(1);
	}

    sem_getvalue(notEnterSem, &semVal);
    if(semVal!=0) {
        printf("You can't enter this room!\n");
        return 0;
    }

    sem_getvalue(clientNum, &semVal);
    if(semVal==0) {
        printf("You can't enter this room!\n");
        return 0;
    }
	
    sem_wait(clientNum);
    sem_getvalue(startSem, &semVal);

	printf("======================\n");
	printf("     Hello %d\n", getpid());
	printf("     Game Start!!\n");
	printf("======================\n");

    sem_post(startSem);

    sem_wait(nowStartGameSem);

    while(1){
       
        sem_getvalue(doOneClient, &semVal);
        if(semVal >= 1){
            sem_wait(doOneClient);

            printf("input num(100~999) : ");
            scanf("%d", &userguessNum);
            ptr1[0] = userguessNum;
            ptr1[1] = getpid();

            sem_post(waitInputSem);

            sem_wait(waitOutputSem);
           
            sem_post(waitPrintSem);

            printf("[%d] %d : %d strike, %d ball\n", ptr1[1], ptr1[0], ptr2[0],
                ptr2[1]);
        
            if(ptr2[0]==3){
                printf("You Win :)\n");
                break;
            }

            sem_wait(doOneClient);


        }
        else{
            sem_wait(waitPrintSem);
            printf("[%d] %d : %d strike, %d ball\n", ptr1[1], ptr1[0], ptr2[0],
                    ptr2[1]);

            if(ptr2[0]==3){
                printf("You Lose :(\n");
                break;
            }

            sem_post(doOneClient);
            sem_post(doOneClient);

        }
    }
	
	close(fd1);
	close(fd2);
    sem_post(clientNum);
}
Exemplo n.º 15
0
void *routine(void *ID){

	int thread_func;
	int j, k, l, value;
	thread_func = (int)ID;

	switch(thread_func){

//	Process 1 to be executed by thread 0

		case 0:	
			for(j=0; j<MIN_EXEC; j++){			
				sem_wait(&semaphore[0]);
				sem_getvalue(&semaphore[0], &value);
				printf("Value of semaphore[0] = %d\n",value);
				sem_wait(&semaphore[0]);
				sem_getvalue(&semaphore[0], &value);
				printf("Value of semaphore[0] = %d\n",value);
				sem_wait(&semaphore[0]);	
				sem_getvalue(&semaphore[0], &value);
				printf("Value of semaphore[0] = %d\n",value);
				printf("Thread: %d\n", thread_func);
				sem_post(&semaphore[1]);	
				sem_getvalue(&semaphore[1], &value);
				printf("Value of semaphore[1] = %d\n", value);

			}	
		break;

//	Process 2 to be executed by thread 1

		case 1:		
			for(k=0; k<MIN_EXEC; k++){
				sem_wait(&semaphore[1]);
				sem_getvalue(&semaphore[1], &value);
				printf("Value of semaphore[1] = %d\n",value);
				printf("Thread: %d\n", thread_func);
				sem_post(&semaphore[2]);
				sem_getvalue(&semaphore[2], &value);
				printf("Value of semaphore[2] = %d\n",value);
				sem_post(&semaphore[0]);
				sem_getvalue(&semaphore[0], &value);
				printf("Value of semaphore[0] = %d\n",value);
			}
		break;

// Process 3 to be executed by thread 2
		case 2:
			for(l=0; l<MIN_EXEC; l++){
				sem_wait(&semaphore[2]);
				sem_getvalue(&semaphore[2], &value);
				printf("Value of semaphore[2] = %d\n",value);
				sem_wait(&semaphore[2]);
				sem_getvalue(&semaphore[2], &value);
				printf("Value of semaphore[2] = %d\n",value);
				sem_wait(&semaphore[2]);	
				sem_getvalue(&semaphore[2], &value);
				printf("Value of semaphore[2] = %d\n",value);
				printf("Thread: %d\n", thread_func);
				sem_post(&semaphore[1]);
				sem_getvalue(&semaphore[1], &value);
				printf("Value of semaphore[1] = %d\n",value);
				sem_post(&semaphore[1]);
				sem_getvalue(&semaphore[1], &value);
				printf("Value of semaphore[1] = %d\n",value);
			}
		break;

		default:
			break;
	}

}
Exemplo n.º 16
0
Arquivo: 3-2.c Projeto: kraj/ltp
/* The main test function. */
int main(void)
{
	int ret, value;

	sem_t *sem;

	/* Initialize output */
	output_init();

	/* Create the semaphore */
	sem = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0777, 2);

	if (sem == SEM_FAILED && errno == EEXIST) {
		sem_unlink(SEM_NAME);
		sem = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0777, 2);
	}

	if (sem == SEM_FAILED) {
		UNRESOLVED(errno, "Failed to create the semaphore");
	}

	/* Use the semaphore to change its value. */
	do {
		ret = sem_wait(sem);
	} while (ret != 0 && errno == EINTR);

	if (ret != 0) {
		UNRESOLVED(errno, "Failed to wait for the semaphore");
	}

	/* Here, count is 1. Now, close the semaphore */
	ret = sem_close(sem);

	if (ret != 0) {
		UNRESOLVED(errno, "Failed to close the semaphore");
	}

	/* Open the semaphore again */
	sem = sem_open(SEM_NAME, O_CREAT, 0777, 3);

	if (sem == SEM_FAILED) {
		UNRESOLVED(errno, "Failed to re-open the semaphore");
	}

	/* Check current semaphore count */
	ret = sem_getvalue(sem, &value);

	if (ret != 0) {
		UNRESOLVED(errno, "Failed to get semaphore value");
	}

	if (value != 1) {
		output("Got value: %d\n", value);
		FAILED("The semaphore count has changed after sem_close");
	}

	/* Now, we can destroy all */
	ret = sem_close(sem);

	if (ret != 0) {
		UNRESOLVED(errno, "Failed to close the semaphore");
	}

	ret = sem_unlink(SEM_NAME);

	if (ret != 0) {
		UNRESOLVED(errno, "Failed to unlink the semaphore");
	}

	/* Test passed */
#if VERBOSE > 0
	output("Test passed\n");

#endif
	PASSED;
}
Exemplo n.º 17
0
int
main()
{
	sem_t sem_a, sem_b;
	pthread_t threads[NTHREADS];
	unsigned i;
	int val;
  
	fprintf(stderr, "Test begin\n");

#ifdef _LIBC_R_
	assert(-1 == sem_init(&sem_b, 1, 0));
	assert(EPERM == errno);
#endif

	assert(0 == sem_init(&sem_b, 0, 0));
	assert(0 == sem_getvalue(&sem_b, &val));
	assert(0 == val);
  
	assert(0 == sem_post(&sem_b));
	assert(0 == sem_getvalue(&sem_b, &val));
	assert(1 == val);
  
	assert(0 == sem_wait(&sem_b));
	assert(-1 == sem_trywait(&sem_b));
	assert(EAGAIN == errno);
	assert(0 == sem_post(&sem_b));
	assert(0 == sem_trywait(&sem_b));
	assert(0 == sem_post(&sem_b));
	assert(0 == sem_wait(&sem_b));
	assert(0 == sem_post(&sem_b));

#ifdef _LIBC_R_
	assert(SEM_FAILED == sem_open("/foo", O_CREAT | O_EXCL, 0644, 0));
	assert(ENOSYS == errno);

	assert(-1 == sem_close(&sem_b));
	assert(ENOSYS == errno);
  
	assert(-1 == sem_unlink("/foo"));
	assert(ENOSYS == errno);
#endif

	assert(0 == sem_destroy(&sem_b));
  
	assert(0 == sem_init(&sem_a, 0, 0));

	for (i = 0; i < NTHREADS; i++) {
		pthread_create(&threads[i], NULL, entry, (void *) &sem_a);
	}

	for (i = 0; i < NTHREADS; i++) {
		assert(0 == sem_post(&sem_a));
	}
  
	for (i = 0; i < NTHREADS; i++) {
		pthread_join(threads[i], NULL);
	}
  
	for (i = 0; i < NTHREADS; i++) {
		pthread_create(&threads[i], NULL, entry, (void *) &sem_a);
	}

	for (i = 0; i < NTHREADS; i++) {
		assert(0 == sem_post(&sem_a));
	}
  
	for (i = 0; i < NTHREADS; i++) {
		pthread_join(threads[i], NULL);
	}
  
	assert(0 == sem_destroy(&sem_a));

	fprintf(stderr, "Test end\n");
	return 0;
}
Exemplo n.º 18
0
int get_online_clients() {
    sem_getvalue(&online_clients, &online_clients_value);
    return online_clients_value;
}
Exemplo n.º 19
0
	int Semaphore::Count()
	{
		int retval;
		sem_getvalue( &sema, &retval );
		return retval;
	}
Exemplo n.º 20
0
int main(void)
{
#ifndef _POSIX_PRIORITY_SCHEDULING
	printf("_POSIX_PRIORITY_SCHEDULING not defined\n");
	return PTS_UNTESTED;
#endif
	sem_t *sem, *sem_1;
	int val;
	int priority;
	pid_t c_1, c_2, c_3, ret_pid;
	int retval = PTS_UNRESOLVED;
	int status;

	snprintf(semname, sizeof(semname), "/" TEST "_%d", getpid());

	sem = sem_open(semname, O_CREAT | O_EXCL, 0777, 1);
	if (sem == SEM_FAILED) {
		perror("sem_open(semname)");
		return PTS_UNRESOLVED;
	}

	snprintf(semname_1, sizeof(semname_1), "/" TEST "_%d_1", getpid());

	sem_1 = sem_open(semname_1, O_CREAT | O_EXCL, 0777, 3);
	if (sem_1 == SEM_FAILED) {
		perror("sem_open(semname_1)");
		sem_unlink(semname);
		return PTS_UNRESOLVED;
	}

	/* The parent has highest priority */
	priority = sched_get_priority_min(SCHED_FIFO) + 3;
	if (set_my_prio(priority) == -1) {
		retval = PTS_UNRESOLVED;
		goto clean_up;
	}

	/* Lock Semaphore */
	if (sem_wait(sem) == -1) {
		perror("sem_wait()");
		retval = PTS_UNRESOLVED;
		goto clean_up;
	}

	c_1 = fork();
	switch (c_1) {
	case 0:
		child_fn(priority - 2, 1);
	break;
	case -1:
		perror("fork()");
		retval = PTS_UNRESOLVED;
		goto clean_up;
	break;
	}
	fprintf(stderr, "P: child_1: %d forked\n", c_1);

	c_2 = fork();
	switch (c_2) {
	case 0:
		child_fn(priority - 1, 2);
	break;
	case -1:
		perror("fork()");
		retval = PTS_UNRESOLVED;
		goto clean_up;
	break;
	}
	fprintf(stderr, "P: child_2: %d forked\n", c_2);

	/* Make sure the two children has been waiting */
	do {
		usleep(100);
		sem_getvalue(sem_1, &val);
	} while (val != 1);
	usleep(100);

	c_3 = fork();
	switch (c_3) {
	case 0:
		child_fn(priority - 1, 3);
	break;
	case -1:
		perror("fork()");
		retval = PTS_UNRESOLVED;
		goto clean_up;
	break;
	}
	fprintf(stderr, "P: child_3: %d forked\n", c_3);

	/* Make sure child 3 has been waiting for the lock */
	do {
		usleep(100);
		sem_getvalue(sem_1, &val);
	} while (val != 0);
	usleep(100);

	/* Ok, let's release the lock */
	fprintf(stderr, "P: release lock\n");
	sem_post(sem);
	ret_pid = wait(&status);
	if (ret_pid == c_2 && WIFEXITED(status)
	    && WEXITSTATUS(status) == 0) {
		fprintf(stderr, "P: release lock\n");
		sem_post(sem);
		ret_pid = wait(&status);
		if (ret_pid == c_3 && WIFEXITED(status)
		    && WEXITSTATUS(status) == 0){
			fprintf(stderr, "P: release lock\n");
			sem_post(sem);
			ret_pid = wait(&status);
			if (ret_pid == c_1 && WIFEXITED(status)
			    && WEXITSTATUS(status) == 0) {
				printf("Test PASSED\n");
				retval = PTS_PASS;
				goto clean_up;
			}
			printf("Test Fail: Expect child_1: %d, got %d\n",
				c_1, ret_pid);
			retval = PTS_FAIL;
			goto clean_up;
		} else {
			printf("Test Fail: Expect child_3: %d, got %d\n",
			c_3, ret_pid);
			retval = PTS_FAIL;
			sem_post(sem);
			while ((wait(NULL) > 0));
			goto clean_up;
		}
	} else {
		printf("Test Fail: Expect child_2: %d, got %d\n",
			c_2, ret_pid);
		retval = PTS_FAIL;
		sem_post(sem);
		sem_post(sem);
		while ((wait(NULL) > 0));
		goto clean_up;
	}

clean_up:
	sem_close(sem);
	sem_close(sem_1);
	sem_unlink(semname);
	sem_unlink(semname_1);
	return retval;
}
Exemplo n.º 21
0
__weak
int __real_sem_getvalue(sem_t * sem, int *sval)
{
	return sem_getvalue(sem, sval);
}
Exemplo n.º 22
0
int semaphore_entry(void)
{
/* para evitar que la función modifique los valores del mensaje recibido, 
 * creamos variables locales de manera de evitar tener que acceder 
 * al mensaje para armar la respuesta, es más ineficiente, pero...
 */
	int return_val;

	sem_t sema;
	sem_t *semaux;
	int pshared, oflags, permission, initial, value_now, argc, phsared;
	char name[MAX_NAME];



#ifdef DEBUG
/*
int i;
char *m1;*/
printf("en el semaphore.c\n");/*
for (i = 0; i < 100; i++)
{
	if ((m1 = malloc(128)) == NULL)
	{
		printf("FALLO MALLOC en la iteracion %d\n", i);
		break;
	}
	strcpy(m1, "malloc\n");
	printf("i = %d m1 = %d m1 = %s\n", i, (int)m1, m1);
}*/
#endif
	


	sema = mensaje_semaforo;
	oflags = mensaje_oflag;
	permission = mensaje_permisos;
	initial = mensaje_valInicial;
	value_now = mensaje_valActual;
	argc = mensaje_cantArg;
	pshared = mensaje_pshared;

	sys_copy (who, D, (phys_bytes) mensaje_nombre, FS_PROC_NR, D,  (phys_bytes) name,  (phys_bytes) MAX_NAME);
	name[MAX_NAME - 1] = '\0';

	switch(mensaje_funcion)
	{
		case SEM_OPEN: if (argc == 4)
			       {
#ifdef DEBUG
printf("SEMOPEN name: %s, oflags: %d, permission: %d, initial: %d\n", name, oflags, permission, initial);
#endif 
					semaux = sem_open(name, oflags, permission,
								   initial);
			       }
			       else
			       {
#ifdef DEBUG
printf("SEMOPEN name: %s, oflags: %d\n", name, oflags);
#endif 
					semaux = sem_open(name, oflags);
			       }
			       answer(*semaux,0,0,1);
			       break;

		case SEM_CLOSE: 
				return_val = sem_close(&sema);
				answer(return_val,sema,0,2);
				break;

		case SEM_INIT:  return_val = sem_init(&sema, pshared, initial);
				answer(return_val,sema,0,2);
				break;

		case SEM_WAIT:  return_val = sem_wait(&sema);
				answer(return_val,sema,0,2);
				break;

		case SEM_POST:  return_val = sem_post(&sema);
				answer(return_val,sema,0,2);
				break;

		case SEM_ULINK: return_val = sem_unlink(name);
				answer(return_val,0,0,1);
				break;

		case SEM_GETVAL: return_val = sem_getvalue(&sema, &value_now);
				 answer(return_val,sema,value_now,3);
				 break;

		case SEM_TRYWAIT: return_val = sem_trywait(&sema);
				  answer(return_val,sema,0,2);
				  break;
 
		case SEM_DESTROY: return_val = sem_destroy(&sema);
				  answer(return_val,sema,0,2);
				  break;

		case SEM_TIMEDWAIT: return_val = no_func();
				    answer(return_val,0,0,1);
				    break;
	}
#ifdef DEBUG
printf("fin de semaphore.c\n");
#endif
	if (return_val != 0)
		return (errno);		
	return(OK);
}
Exemplo n.º 23
0
int pipecommon_open(FAR struct file *filep)
{
  FAR struct inode      *inode = filep->f_inode;
  FAR struct pipe_dev_s *dev   = inode->i_private;
  int                sval;
  int                ret;

  DEBUGASSERT(dev != NULL);

  /* Make sure that we have exclusive access to the device structure.  The
   * sem_wait() call should fail only if we are awakened by a signal.
   */

  ret = sem_wait(&dev->d_bfsem);
  if (ret != OK)
    {
      fdbg("sem_wait failed: %d\n", get_errno());
      DEBUGASSERT(get_errno() > 0);
      return -get_errno();
    }

  /* If this the first reference on the device, then allocate the buffer.
   * In the case of policy 1, the buffer already be present when the pipe
   * is first opened.
   */

  if (dev->d_refs == 0 && dev->d_buffer == NULL)
    {
      dev->d_buffer = (FAR uint8_t *)kmm_malloc(CONFIG_DEV_PIPE_SIZE);
      if (!dev->d_buffer)
        {
          (void)sem_post(&dev->d_bfsem);
          return -ENOMEM;
        }
    }

  /* Increment the reference count on the pipe instance */

  dev->d_refs++;

  /* If opened for writing, increment the count of writers on the pipe instance */

  if ((filep->f_oflags & O_WROK) != 0)
    {
      dev->d_nwriters++;

      /* If this this is the first writer, then the read semaphore indicates the
       * number of readers waiting for the first writer.  Wake them all up.
       */

      if (dev->d_nwriters == 1)
        {
          while (sem_getvalue(&dev->d_rdsem, &sval) == 0 && sval < 0)
            {
              sem_post(&dev->d_rdsem);
            }
        }
    }

  /* If opened for reading, increment the count of reader on on the pipe instance */

  if ((filep->f_oflags & O_RDOK) != 0)
    {
      dev->d_nreaders++;
    }

  /* If opened for read-only, then wait for either (1) at least one writer
   * on the pipe (policy == 0), or (2) until there is buffered data to be
   * read (policy == 1).
   */

  sched_lock();
  (void)sem_post(&dev->d_bfsem);

  if ((filep->f_oflags & O_RDWR) == O_RDONLY &&  /* Read-only */
      dev->d_nwriters < 1 &&                     /* No writers on the pipe */
      dev->d_wrndx == dev->d_rdndx)              /* Buffer is empty */
    {
      /* NOTE: d_rdsem is normally used when the read logic waits for more
       * data to be written.  But until the first writer has opened the
       * pipe, the meaning is different: it is used prevent O_RDONLY open
       * calls from returning until there is at least one writer on the pipe.
       * This is required both by spec and also because it prevents
       * subsequent read() calls from returning end-of-file because there is
       * no writer on the pipe.
       */

      ret = sem_wait(&dev->d_rdsem);
      if (ret != OK)
        {
          /* The sem_wait() call should fail only if we are awakened by
           * a signal.
           */

          fdbg("sem_wait failed: %d\n", get_errno());
          DEBUGASSERT(get_errno() > 0);
          ret = -get_errno();

          /* Immediately close the pipe that we just opened */

          (void)pipecommon_close(filep);
        }
    }

  sched_unlock();
  return ret;
}
Exemplo n.º 24
0
/* The main test function. */
int main( int argc, char * argv[] )
{
	int ret, value;

	sem_t * sem1, * sem2;

	/* Initialize output */
	output_init();

	/* Create the semaphore */
	sem1 = sem_open( SEM_NAME, O_CREAT | O_EXCL, 0777, 1 );

	if ( ( sem1 == SEM_FAILED ) && ( errno == EEXIST ) )
	{
		sem_unlink( SEM_NAME );
		sem1 = sem_open( SEM_NAME, O_CREAT | O_EXCL, 0777, 1 );
	}

	if ( sem1 == SEM_FAILED )
	{
		UNRESOLVED( errno, "Failed to create the semaphore" );
	}

	/* Unlink */
	ret = sem_unlink( SEM_NAME );

	if ( ret != 0 )
	{
		UNRESOLVED( errno, "Failed to unlink the semaphore" );
	}

	/* Try reconnect */
	sem2 = sem_open( SEM_NAME, 0 );

	if ( sem2 != SEM_FAILED )
	{
		FAILED( "Reconnecting the unlinked semaphore did not failed" );
	}

	if ( errno != ENOENT )
	{
		output( "Error %d: %s\n", errno, strerror( errno ) );
		FAILED( "Reconnecting the unlinked semaphore failed with a wrong error" );
	}

	/* Reopen the semaphore */
	sem2 = sem_open( SEM_NAME, O_CREAT | O_EXCL, 0777, 3 );

	if ( sem2 == SEM_FAILED )
	{
		output( "Gor error %d: %s\n", errno, strerror( errno ) );
		FAILED( "Failed to recreate the semaphore" );
	}

	/* Check the semaphore have different values */
	ret = sem_getvalue( sem1, &value );

	if ( ret != 0 )
	{
		UNRESOLVED( errno, "Failed to read sem1 value" );
	}

	if ( value != 1 )
	{
		output( "Read: %d\n", value );
		FAILED( "Semaphore value is not as expected" );
	}

	ret = sem_getvalue( sem2, &value );

	if ( ret != 0 )
	{
		UNRESOLVED( errno, "Failed to read sem1 value" );
	}

	if ( value != 3 )
	{
		output( "Read: %d\n", value );
		FAILED( "Semaphore value is not as expected" );
	}

	/* Unlink */
	ret = sem_unlink( SEM_NAME );

	if ( ret != 0 )
	{
		UNRESOLVED( errno, "Failed to unlink the semaphore" );
	}

	/* close both */
	ret = sem_close( sem1 );

	if ( ret != 0 )
	{
		UNRESOLVED( errno, "Failed to close the semaphore" );
	}

	ret = sem_close( sem2 );

	if ( ret != 0 )
	{
		UNRESOLVED( errno, "Failed to close the semaphore" );
	}


	/* Test passed */
#if VERBOSE > 0
	output( "Test passed\n" );

#endif
	PASSED;
}
Exemplo n.º 25
0
ssize_t pipecommon_read(FAR struct file *filep, FAR char *buffer, size_t len)
{
  FAR struct inode      *inode  = filep->f_inode;
  FAR struct pipe_dev_s *dev    = inode->i_private;
#ifdef CONFIG_DEV_PIPEDUMP
  FAR uint8_t           *start  = (FAR uint8_t *)buffer;
#endif
  ssize_t            nread  = 0;
  int                sval;
  int                ret;

  DEBUGASSERT(dev);

  if (len == 0)
    {
      return 0;
    }

  /* Make sure that we have exclusive access to the device structure */

  if (sem_wait(&dev->d_bfsem) < 0)
    {
      return ERROR;
    }

  /* If the pipe is empty, then wait for something to be written to it */

  while (dev->d_wrndx == dev->d_rdndx)
    {
      /* If O_NONBLOCK was set, then return EGAIN */

      if (filep->f_oflags & O_NONBLOCK)
        {
          sem_post(&dev->d_bfsem);
          return -EAGAIN;
        }

      /* If there are no writers on the pipe, then return end of file */

      if (dev->d_nwriters <= 0)
        {
          sem_post(&dev->d_bfsem);
          return 0;
        }

      /* Otherwise, wait for something to be written to the pipe */

      sched_lock();
      sem_post(&dev->d_bfsem);
      ret = sem_wait(&dev->d_rdsem);
      sched_unlock();

      if (ret < 0  || sem_wait(&dev->d_bfsem) < 0)
        {
          return ERROR;
        }
    }

  /* Then return whatever is available in the pipe (which is at least one byte) */

  nread = 0;
  while ((size_t)nread < len && dev->d_wrndx != dev->d_rdndx)
    {
      *buffer++ = dev->d_buffer[dev->d_rdndx];
      if (++dev->d_rdndx >= CONFIG_DEV_PIPE_SIZE)
        {
          dev->d_rdndx = 0;
        }
      nread++;
    }

  /* Notify all waiting writers that bytes have been removed from the buffer */

  while (sem_getvalue(&dev->d_wrsem, &sval) == 0 && sval < 0)
    {
      sem_post(&dev->d_wrsem);
    }

  /* Notify all poll/select waiters that they can write to the FIFO */

  pipecommon_pollnotify(dev, POLLOUT);

  sem_post(&dev->d_bfsem);
  pipe_dumpbuffer("From PIPE:", start, nread);
  return nread;
}
Exemplo n.º 26
0
void print()
{
    printf("I get it,my tid is %d\n",(int)pthread_self());
    sem_getvalue(sem,&val);
    printf("Now the value have %d\n",val);
}
Exemplo n.º 27
0
int  DSema_GetValue( DSema *self )
{
	int n;
	sem_getvalue( & self->mySema, & n );
	return n;
}
Exemplo n.º 28
0
int main(int argc, char *argv[])
{
    signal(SIGINT, quitHandler);
    signal(SIGTERM, quitHandler);
    signal(SIGKILL, quitHandler);

    // validate arguments from command line ------------------------------------
    if (argc < 3) {
	printf("Insufficient arguments.\n");
	return -1;
    }

    else if (strlen(argv[1]) > 5) {
	printf("error: Client ID too long\n");
	return -1;
    }

    else if (is_valid_num(argv[2]) < 0) {
	printf("error: Number of pages is not a positive integer\n");
	return -1;
    }

    // open shared memory segment as if it was a file --------------------------
    shm_fd = shm_open(name, O_RDWR, 0666);
    if (shm_fd == -1) {
	printf("cons: Shared memory failed: %s\n", strerror(errno));
	exit(1);
    }

    // map shared memory segment to address space of process -------------------
    shm_base = (job_control *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (shm_base == MAP_FAILED) {
	printf("cons: Map failed: %s\n", strerror(errno));
	close_unlink();
	exit(1);
    }

    // access variables in shared memory ----------------------------------------
    void *ptr = shm_base;
    sem_t *empty = (sem_t *)ptr;

    ptr += sizeof(sem_t);
    sem_t *mutex = (sem_t *)ptr;

    ptr += sizeof(sem_t);
    sem_t *full = (sem_t *)ptr;

    ptr += sizeof(sem_t);
    int slots = *(int *)ptr;

    ptr += sizeof(int);
    int *queue_in = (int *)ptr;

    ptr += sizeof(int);
    int *queue_out = (int *)ptr;

    ptr += sizeof(int);
    job_t *job_queue = (job_t *)ptr;


    // put job in queue ---------------------------------------------------------
    if (sem_trywait(empty) == -1) {
	printf("Client %s has %s pages to print, buffer full, sleeps\n", argv[1], argv[2]);
	sem_wait(empty);
	printf("Client %s wakes up, puts request in Buffer[%d]\n", argv[1], *queue_in);
    }
    else
	printf("Client %s has %s pages to print, puts request in Buffer[%d]\n", argv[1], argv[2], *queue_in);

    sem_wait(mutex);

    int sem_val = 0;
    job_queue += *queue_in * sizeof(job_t);
    memcpy(job_queue->client_ID, argv[1], MAX_ID*sizeof(char));
    sscanf(argv[2], "%d", &(job_queue->pages));
    *queue_in = (*queue_in + 1) % slots;
    sem_getvalue(full, &sem_val);

    sem_post(mutex);
    sem_post(full);


    // release shared memory ----------------------------------------------------
    close_unlink();

    return 0;
}
/**
 * TODO free and close/DESTORY all the semaphores before exit !!!
 *
 */
void init_socketChannel()
{

	int i;
	 /** Notice that the main_channel_Semaphore is a semaphore shared among processes
	  * (It is processes level semaphore, NOT threads level)
	  */

	/** Needs NPTL because LinuxThreads does not support sharing semaphores between processes */


	/** the semaphore is initially locked */

	//main_channel_semaphore1 = sem_open(main_sem_name1,O_CREAT|O_EXCL,0644,0);
	main_channel_semaphore1 = sem_open(main_sem_name1,0,0644,0);
	PRINT_DEBUG();
	if (main_channel_semaphore1 == SEM_FAILED)
	{

		main_channel_semaphore1 = sem_open(main_sem_name1,0);
		PRINT_DEBUG();

	}
	 if(main_channel_semaphore1 == SEM_FAILED)
	    {
	      perror("unable to create semaphore");
	      sem_unlink(main_sem_name1);
	      exit(-1);
	    }

	// main_channel_semaphore2 = sem_open(main_sem_name2,O_CREAT|O_EXCL,0644,0);
	 main_channel_semaphore2 = sem_open(main_sem_name2,0,0644,0);
	 PRINT_DEBUG();
	 if (main_channel_semaphore2 == SEM_FAILED)
	 	{
	 		main_channel_semaphore2 = sem_open(main_sem_name2,0);
	 		PRINT_DEBUG();

	 	}
	 	 if(main_channel_semaphore2 == SEM_FAILED)
	 	    {
	 	      perror("unable to create semaphore");
	 	      sem_unlink(main_sem_name2);
	 	      exit(-1);
	 	    }



	 PRINT_DEBUG("111");

	//	mkfifo(MAIN_SOCKET_CHANNEL,0777);
		socket_channel_desc = open (MAIN_SOCKET_CHANNEL,O_WRONLY);

	 int tester;
	 sem_getvalue(main_channel_semaphore1,&tester);
	 PRINT_DEBUG("tester = %d",tester);
	//sem_wait(main_channel_semaphore);
	 PRINT_DEBUG("222");


	 PRINT_DEBUG("333");

	/** initialize the sockets database
	 * this is a simplified version from the full detailed database available
	 * on the socket jinni side
	 * */

	sem_init(&FinsHistory_semaphore,1,1);
  		for (i=0;i<MAX_sockets;i++)
  		{
		FinsHistory[i].processID = -1;
		FinsHistory[i].socketDesc = -1;
		FinsHistory[i].fakeID = -1;

  		}



}
Exemplo n.º 30
0
int Semaphore::GetValue(int& i)
{
	return sem_getvalue(&m_sem, &i);
}