当前位置: 首页>>代码示例>>C++>>正文


C++ sem_wait函数代码示例

本文整理汇总了C++中sem_wait函数的典型用法代码示例。如果您正苦于以下问题:C++ sem_wait函数的具体用法?C++ sem_wait怎么用?C++ sem_wait使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了sem_wait函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: sem_wait

Mail* Mailbox::Pend() {
    sem_wait(&semInside);
    Mail* mail = mailBuffer.front();
    mailBuffer.pop();
    return mail;
}
开发者ID:AfkMan,项目名称:NeeTechLibrary,代码行数:6,代码来源:Mailbox.cpp

示例2: main

int main(int argc, char *argv[]){
	
	//Creates semaphore that will be used to avoid writting at the same time as other threads
	sem_t *semaphore = sem_open(SEM, O_CREAT ,0660,1);
	
	//Checks for number of arguments
	if(argc != 3)
	{
		printf("Invalid number of arguments!\n Correct usage: parque <int num_Lugares> <int open_time>\nn");
		perror("Argument Number");
		exit(1);
	}

	//converts inputs from string to int and saves in global variable
	n_lugares = atoi(argv[1]);
	t_abertura = atoi(argv[2]);

	//checks if inputs are valid
	if(n_lugares < 1){
		printf("error: n_lugares < 1");
		perror("n_lugares must be an integer bigger than 0");
		exit(1);
	}
	if(t_abertura < 1){
		printf("error: t_abertura < 1");
		perror("t_abertura must be an integer bigger than 0");
		exit(1);
	}

	time_t start, current;
	//Saves the starting time
	time(&start);

	//Creates fifos for each entrance
	mkfifo("fifoN",FIFO_PERMISSIONS);
	mkfifo("fifoS",FIFO_PERMISSIONS);
	mkfifo("fifoE",FIFO_PERMISSIONS);
	mkfifo("fifoW",FIFO_PERMISSIONS);

	
	//A char for each of the entrances, used in creating controller threads
	char NN = 'N';
	char SS = 'S';
	char EE = 'E';
	char WW = 'W';
	
	//Creates the parque.log file
	pLog = fopen("parque.log", "w");
	
	//Prints the log header
	fprintf(pLog, "  t(ticks) ;   nLug    ;   id_viat ;   observs\n");

	
	//Prepares thread variable and attributes
	pthread_t t;
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);


	//Creates thread 'controlador' North
	if((pthread_create(&t, &attr, &controlador, &NN)) != 0){
		printf("Error creating new 'controlador' thread\n");
		perror("Creating thread");
		exit(THREAD_EXIT);
	}

	//Creates thread 'controlador' South
	if((pthread_create(&t, &attr, &controlador, &SS)) != 0){
		printf("Error creating new 'controlador' thread\n");
		perror("Creating thread");
		exit(THREAD_EXIT);
	}

	//Creates thread 'controlador' East
	if((pthread_create(&t, &attr, &controlador, &EE)) != 0){
		printf("Error creating new 'controlador' thread\n");
		perror("Creating thread");
		exit(THREAD_EXIT);
	}

	//Creates thread 'controlador' West
	if((pthread_create(&t, &attr, &controlador, &WW)) != 0){
		printf("Error creating new 'controlador' thread\n");
		perror("Creating thread");
		exit(THREAD_EXIT);
	}
	
	//Sleeps for the duration that it is supposed to be opened
	sleep(t_abertura);
	
	//Only this or a thread can write to the controller's fifo at any given time
	sem_wait(semaphore);
	
	//Opens controllers' fifos for writing
	int fdN = open("fifoN", O_WRONLY);
	int fdS = open("fifoS", O_WRONLY);
	int fdE = open("fifoE", O_WRONLY);
	int fdW = open("fifoW", O_WRONLY);
	
//.........这里部分代码省略.........
开发者ID:pedro-c,项目名称:SOPE-PROJ-FEUP,代码行数:101,代码来源:parque.c

示例3: UpnpChannelManager_RegisterChannel

// Called by the UPnP Remote I/O Microstack
// Implements the RegisterChannel call, lets the CP register a new RIO channels for a
// certain amont of time. The CP must re-register the channel from time-to-time to
// prevent the channel from expiring.
void UpnpChannelManager_RegisterChannel(void* upnptoken,char* Name,char* PeerConnection,int Timeout)
{
	// Scan the channel list for an existing channel
	struct RemoteIOChannel* channelindex = RIO->ChannelList;
	struct RemoteIOChannel* newchannel;

	printf("RegisterChannel (%d): %s\r\n",Timeout,Name);

	if (PeerConnection == NULL)
	{
		if (upnptoken != NULL) UpnpResponse_Error(upnptoken,800,"Invalid PeerConnection URI");
		return;
	}

	sem_wait(&RemoteIOLock);

	while (channelindex != NULL)
	{
		// Look for a match
		if (strcmp(channelindex->uri,PeerConnection) == 0) break;
		channelindex = channelindex->next;
	}

	if (channelindex != NULL)
	{
		// Update the expiration time
		ILibLifeTime_Remove(RIO->RIOLifeTime,channelindex);
		#ifdef _WIN32_WCE
			channelindex->expiration = (GetTickCount() / 1000) + Timeout;
			ILibLifeTime_Add(RIO->RIOLifeTime,channelindex,Timeout,&RemoteIO_ChannelExpireSink, NULL);
		#elif WIN32
			channelindex->expiration = (GetTickCount() / 1000) + Timeout;
			ILibLifeTime_Add(RIO->RIOLifeTime,channelindex,Timeout,&RemoteIO_ChannelExpireSink, NULL);
		#elif _POSIX
			gettimeofday(&(channelindex->expiration),NULL);
			(channelindex->expiration).tv_sec += (int)Timeout;
			ILibLifeTime_Add(RIO->RIOLifeTime,channelindex,Timeout,&RemoteIO_ChannelExpireSink, NULL);
		#endif
	}
	else
	{
		// Add a new channel to the channel list
		newchannel = (struct RemoteIOChannel*)RIO_MALLOC(sizeof(struct RemoteIOChannel));
		newchannel->name = (char*)RIO_MALLOC(strlen(Name)+1);
		strcpy(newchannel->name,Name);
		newchannel->uri = (char*)RIO_MALLOC(strlen(PeerConnection)+1);
		strcpy(newchannel->uri,PeerConnection);
		#ifdef _WIN32_WCE
			newchannel->expiration = (GetTickCount() / 1000) + Timeout;
			ILibLifeTime_Add(RIO->RIOLifeTime,newchannel,Timeout,&RemoteIO_ChannelExpireSink, NULL);
		#elif WIN32
			newchannel->expiration = (GetTickCount() / 1000) + Timeout;
			ILibLifeTime_Add(RIO->RIOLifeTime,newchannel,Timeout,&RemoteIO_ChannelExpireSink, NULL);
		#elif _POSIX
			gettimeofday(&(newchannel->expiration),NULL);
			(newchannel->expiration).tv_sec += (int)Timeout;
			ILibLifeTime_Add(RIO->RIOLifeTime,newchannel,Timeout,&RemoteIO_ChannelExpireSink, NULL);
		#endif
		newchannel->next = RIO->ChannelList;
		RIO->ChannelList = newchannel;

		// Set the channels to be evented
		if (RIO->EventModerationSet == 0)
		{
			ILibLifeTime_Add(RIO->RIOLifeTime,NULL,2,&RemoteIO_EventChannelList, NULL);
			RIO->EventModerationSet = 1;
		}
	}

	UpnpResponse_ChannelManager_RegisterChannel(upnptoken);

	sem_post(&RemoteIOLock);
}
开发者ID:optman,项目名称:upnpstack,代码行数:77,代码来源:RemoteIOClientStack.c

示例4: escalonar

void escalonar(int tempoExec){

	int i=0;

	sem_wait(&semEscalonador);
	if(tempoExec > 0){
		printf("#-----------------------------------------------------------------------------------------#\n");
		printf("#-----------------------------------------------------------------------------------------#\n\n");
		if(executando == 0){
			printf("Iniciando execução \n");
			executando = 1;

			switch(Dados.Prioridade){
				case 1:
					Fila1 = Remove(Fila1);
					emExecucao = Insere(emExecucao,Dados.PID,Dados.Prioridade);

					printf("Executando processo por 100 ut \n");
					for(i=0;i<3;i++){
						printf("Executando processo ... \n");
						sleep(2);
					}
					tempoExec = tempoExec - 100;
					emExecucao = Remove(emExecucao);

					if(tempoExec > 0){
						trataInterrupcao(1);
					}else{
						trataInterrupcao(3);
					}

					break;

				case 2:
					Fila2 = Remove(Fila2);
					emExecucao = Insere(emExecucao,Dados.PID,Dados.Prioridade);

					printf("Executando processo por 200 ut \n");
					for(i=0;i<3;i++){
						printf("Executando processo ... \n");
						sleep(2);
					}
					tempoExec = tempoExec - 200;
					emExecucao = Remove(emExecucao);

					if(tempoExec > 0){
						trataInterrupcao(1);
					}else{
						trataInterrupcao(3);
				    }

					break;

				case 3:
					Fila3 = Remove(Fila3);
					emExecucao = Insere(emExecucao,Dados.PID,Dados.Prioridade);

					printf("Executando processo por 400 ut \n");
					for(i=0;i<3;i++){
						printf("Executando processo ... \n");
						sleep(2);
					}
					tempoExec = tempoExec - 400;
					emExecucao = Remove(emExecucao);

					if(tempoExec > 0){
						trataInterrupcao(1);
					}else{
						trataInterrupcao(3);
					}

					break;

				case 4:
					Fila2 = Remove(Fila2);
					emExecucao = Insere(emExecucao,Dados.PID,Dados.Prioridade);

					printf("Executando processo por 600 ut \n");
					for(i=0;i<3;i++){
						printf("Executando processo ... \n");
						sleep(2);
					}
					tempoExec = tempoExec - 600;
					emExecucao = Remove(emExecucao);

					if(tempoExec > 0){
						trataInterrupcao(1);
					}else{
						trataInterrupcao(3);
					}

					break;

				case 5:
					Fila2 = Remove(Fila2);
					emExecucao = Insere(emExecucao,Dados.PID,Dados.Prioridade);

					printf("Executando processo por 100 ut \n");
					for(i=0;i<3;i++){
						printf("Executando processo ... \n");
//.........这里部分代码省略.........
开发者ID:renanalboy,项目名称:Trabalhos-Graduacao,代码行数:101,代码来源:nucleo.c

示例5: main

void main (int argc, char *argv[])
{
  int numprocs = 0;               // Used to store number of processes to create
  int i;                          // Loop index variable
  missile_code *mc;               // Used to get address of shared memory page
  uint32 h_mem;                   // Used to hold handle to shared memory page
  sem_t s_procs_completed;        // Semaphore used to wait until all spawned processes have completed
  char h_mem_str[10];             // Used as command-line argument to pass mem_handle to new processes
  char s_procs_completed_str[10]; // Used as command-line argument to pass page_mapped handle to new processes

  if (argc != 2) {
    Printf("Usage: "); Printf(argv[0]); Printf(" <number of processes to create>\n");
    Exit();
  }

  // Convert string from ascii command line argument to integer number
  numprocs = dstrtol(argv[1], NULL, 10); // the "10" means base 10
  Printf("Creating %d processes\n", numprocs);

  // Allocate space for a shared memory page, which is exactly 64KB
  // Note that it doesn't matter how much memory we actually need: we 
  // always get 64KB
  if ((h_mem = shmget()) == 0) {
    Printf("ERROR: could not allocate shared memory page in "); Printf(argv[0]); Printf(", exiting...\n");
    Exit();
  }

  // Map shared memory page into this process's memory space
  if ((mc = (missile_code *)shmat(h_mem)) == NULL) {
    Printf("Could not map the shared page to virtual address in "); Printf(argv[0]); Printf(", exiting..\n");
    Exit();
  }

  // Put some values in the shared memory, to be read by other processes
  mc->numprocs = numprocs;
  mc->really_important_char = 'A';

  // Create semaphore to not exit this process until all other processes 
  // have signalled that they are complete.  To do this, we will initialize
  // the semaphore to (-1) * (number of signals), where "number of signals"
  // should be equal to the number of processes we're spawning - 1.  Once 
  // each of the processes has signaled, the semaphore should be back to
  // zero and the final sem_wait below will return.
  if ((s_procs_completed = sem_create(-(numprocs-1))) == SYNC_FAIL) {
    Printf("Bad sem_create in "); Printf(argv[0]); Printf("\n");
    Exit();
  }

  // Setup the command-line arguments for the new process.  We're going to
  // pass the handles to the shared memory page and the semaphore as strings
  // on the command line, so we must first convert them from ints to strings.
  ditoa(h_mem, h_mem_str);
  ditoa(s_procs_completed, s_procs_completed_str);

  // Now we can create the processes.  Note that you MUST end your call to
  // process_create with a NULL argument so that the operating system
  // knows how many arguments you are sending.
  for(i=0; i<numprocs; i++) {
    Printf("h_mem_str : %s semaphore_str : %s", h_mem_str, s_procs_completed_str);
    
    process_create(FILENAME_TO_RUN, h_mem_str, s_procs_completed_str, NULL);
    Printf("Process %d created\n", i);
  }

  // And finally, wait until all spawned processes have finished.
  if (sem_wait(s_procs_completed) != SYNC_SUCCESS) {
    Printf("Bad semaphore s_procs_completed (%d) in ", s_procs_completed); Printf(argv[0]); Printf("\n");
    Exit();
  }
  Printf("All other processes completed, exiting main process.\n");
}
开发者ID:aggarw13,项目名称:ECE469_Operating_Systems,代码行数:71,代码来源:makeprocs.c

示例6: main


//.........这里部分代码省略.........
		Error(1); // Error has occurred
	}

	// Opens shared memory between two processes

	shmid1 = shm_get(900001, (void*) &BufferA, 22);

	// Opens shared memory between two processes

	shmid2 = shm_get(900002, (void*) &BufferB, 69);


	// Create duplicate processes and give them code for processes X and Y

	pX = fork();

	if (pX == 0) // process is a child
	{
		execv("ProcX", arg);
	}

	pY = fork();

	if (pY == 0) // process is a child
	{
		execv("ProcY", arg);
	}


	// Synchronize with ProcX and ProcY

	temp = sem_signal(semX);
	temp = sem_signal(semY);
	temp = sem_wait(semZ);
	temp = sem_wait(semZ);


	// Take out items from buffers when elements exist

	counter = 1;
	input = 0;

	while (counter <= 260)
	{
		// Wait until both of the buffers have been filled

		temp = sem_wait(CSZ);
		temp = sem_wait(CSZ);

		// Remove one item from BufferA when one exists

		temp = sem_wait(bufAFilled);

		c1 = BufferA[input*2];
		c2 = BufferA[input*2+1];

		printf("+ %c%c +", c1, c2);

		temp = sem_signal(bufAEmpty);

		// Remove one item from BufferB when one exists

		temp = sem_wait(bufBFilled);

		c1 = BufferB[input*3];
		c2 = BufferB[input*3+1];
开发者ID:stevenharman,项目名称:osu-cis,代码行数:67,代码来源:Lab3+-+ProcZ.c

示例7: rping_test_client

static int rping_test_client(struct rping_cb *cb)
{
	int ping, start, cc, i, ret = 0;
	struct ibv_send_wr *bad_wr;
	unsigned char c;

	start = 65;
	for (ping = 0; !cb->count || ping < cb->count; ping++) {
		cb->state = RDMA_READ_ADV;

		/* Put some ascii text in the buffer. */
		cc = sprintf(cb->start_buf, RPING_MSG_FMT, ping);
		for (i = cc, c = start; i < cb->size; i++) {
			cb->start_buf[i] = c;
			c++;
			if (c > 122)
				c = 65;
		}
		start++;
		if (start > 122)
			start = 65;
		cb->start_buf[cb->size - 1] = 0;

		rping_format_send(cb, cb->start_buf, cb->start_mr);
		ret = ibv_post_send(cb->qp, &cb->sq_wr, &bad_wr);
		if (ret) {
			fprintf(stderr, "post send error %d\n", ret);
			break;
		}

		/* Wait for server to ACK */
		sem_wait(&cb->sem);
		if (cb->state != RDMA_WRITE_ADV) {
			fprintf(stderr, "wait for RDMA_WRITE_ADV state %d\n",
				cb->state);
			ret = -1;
			break;
		}

		rping_format_send(cb, cb->rdma_buf, cb->rdma_mr);
		ret = ibv_post_send(cb->qp, &cb->sq_wr, &bad_wr);
		if (ret) {
			fprintf(stderr, "post send error %d\n", ret);
			break;
		}

		/* Wait for the server to say the RDMA Write is complete. */
		sem_wait(&cb->sem);
		if (cb->state != RDMA_WRITE_COMPLETE) {
			fprintf(stderr, "wait for RDMA_WRITE_COMPLETE state %d\n",
				cb->state);
			ret = -1;
			break;
		}

		if (cb->validate)
			if (memcmp(cb->start_buf, cb->rdma_buf, cb->size)) {
				fprintf(stderr, "data mismatch!\n");
				ret = -1;
				break;
			}

		if (cb->verbose)
			printf("ping data: %s\n", cb->rdma_buf);
	}

	return ret;
}
开发者ID:2014-class,项目名称:freerouter,代码行数:68,代码来源:rping.c

示例8: s_lock

int s_lock(struct slock *sp){
    return sem_wait(sp->semp);
}
开发者ID:geassdai,项目名称:APUE,代码行数:3,代码来源:sem.c

示例9: wait

 void wait() {
   fprintf(stderr, "NandSim::wait for semaphore\n");
   sem_wait(&sem);
 }
开发者ID:chamdoo,项目名称:xbsv,代码行数:4,代码来源:testnandsim_test.cpp

示例10: main

int
main(int argc, char *argv[])
{
	const char *ethername, *ethername_ro;
	const char *serveraddr, *serveraddr_ro;
	const char *netmask;
	const char *exportpath;
	const char *imagename;
	char ifname[IFNAMSIZ], ifname_ro[IFNAMSIZ];
	void *fsarg;
	pthread_t t;
	int rv;

	/* for netcfg */
	noatf = 1;

	/* use defaults? */
	if (argc == 1) {
		ethername = "etherbus";
		ethername_ro = "etherbus_ro";
		serveraddr = "10.3.2.1";
		serveraddr_ro = "10.4.2.1";
		netmask = "255.255.255.0";
		exportpath = "/myexport";
		imagename = "ffs.img";
	} else {
		ethername = argv[1];
		ethername_ro = argv[2];
		serveraddr = argv[3];
		serveraddr_ro = argv[4];
		netmask = argv[5];
		exportpath = argv[6];
		imagename = argv[7];
	}

	rump_init();
	svc_fdset_init(SVC_FDSET_MT);

	rv = rump_pub_etfs_register("/etc/exports", "./exports", RUMP_ETFS_REG);
	if (rv) {
		errx(1, "register /etc/exports: %s", strerror(rv));
	}

	/* mini-mtree for mountd */
	static const char *const dirs[] = { "/var", "/var/run", "/var/db" };
	for (size_t i = 0; i < __arraycount(dirs); i++)
		if (rump_sys_mkdir(dirs[i], 0777) == -1)
			err(1, "can't mkdir `%s'", dirs[i]);

	if (ffs_fstest_newfs(NULL, &fsarg,
	    imagename, FSTEST_IMGSIZE, NULL) != 0)
		err(1, "newfs failed");
	if (ffs_fstest_mount(NULL, fsarg, exportpath, 0) != 0)
		err(1, "mount failed");

#if 0
	/*
	 * Serve from host instead of dedicated mount?
	 * THIS IS MORE EVIL THAN MURRAY THE DEMONIC TALKING SKULL!
	 */

	if (ukfs_modload("/usr/lib/librumpfs_syspuffs.so") < 1)
		errx(1, "modload");

	mount_syspuffs_parseargs(__arraycount(pnullarg), pnullarg,
	    &args, &mntflags, canon_dev, canon_dir);
	if ((ukfs = ukfs_mount(MOUNT_PUFFS, "/", UKFS_DEFAULTMP, MNT_RDONLY,
	    &args, sizeof(args))) == NULL)
		err(1, "mount");

	if (ukfs_modload("/usr/lib/librumpfs_nfsserver.so") < 1)
		errx(1, "modload");
#endif

	if (sem_init(&gensem, 1, 0) == -1)
		err(1, "gensem init");

	/* create interface */
	netcfg_rump_makeshmif(ethername, ifname);
	netcfg_rump_if(ifname, serveraddr, netmask);

	netcfg_rump_makeshmif(ethername_ro, ifname_ro);
	netcfg_rump_if(ifname_ro, serveraddr_ro, netmask);

	/*
	 * No syslogging, thanks.
	 * XXX: "0" does not modify the mask, so pick something
	 * which is unlikely to cause any logging
	 */
	setlogmask(0x10000000);

	if (pthread_create(&t, NULL, rpcbind_main, NULL) == -1)
		err(1, "rpcbind");
	sem_wait(&gensem);

	if (pthread_create(&t, NULL, mountd_main, NULL) == -1)
		err(1, "mountd");
	sem_wait(&gensem);

	rv = 0;
//.........这里部分代码省略.........
开发者ID:2trill2spill,项目名称:freebsd,代码行数:101,代码来源:rumpnfsd.c

示例11: begin_write

void begin_write(struct lectred* l) {
	sem_wait(&(l->ecriture));
}
开发者ID:LilyOfTheWest,项目名称:M1-Info,代码行数:3,代码来源:exo2_2.c

示例12: AcpiOsWaitSemaphore

ACPI_STATUS
AcpiOsWaitSemaphore (
    ACPI_HANDLE         Handle,
    UINT32              Units,
    UINT16              Timeout)
{
    ACPI_STATUS         Status = AE_OK;

#if 0
    if (!Sem)
    {
        return (AE_BAD_PARAMETER);
    }

    switch (Timeout)
    {
    /*
     * No Wait:
     * --------
     * A zero timeout value indicates that we shouldn't wait - just
     * acquire the semaphore if available otherwise return AE_TIME
     * (a.k.a. 'would block').
     */
    case 0:

        if (sem_trywait(Sem) == -1)
        {
            Status = (AE_TIME);
        }
        break;

    /* Wait Indefinitely */

    case ACPI_WAIT_FOREVER:

        if (sem_wait (Sem))
        {
            Status = (AE_TIME);
        }
        break;

    /* Wait with Timeout */

    default:

        T.tv_sec = Timeout / 1000;
        T.tv_nsec = (Timeout - (T.tv_sec * 1000)) * 1000000;

#ifdef ACPI_USE_ALTERNATE_TIMEOUT
        /*
         * Alternate timeout mechanism for environments where
         * sem_timedwait is not available or does not work properly.
         */
        while (Timeout)
        {
            if (sem_trywait (Sem) == 0)
            {
                /* Got the semaphore */
                return (AE_OK);
            }
            usleep (1000);  /* one millisecond */
            Timeout--;
        }
        Status = (AE_TIME);
#else

        if (sem_timedwait (Sem, &T))
        {
            Status = (AE_TIME);
        }
#endif

        break;
    }
#endif

    return (Status);
}
开发者ID:Xeffyr,项目名称:KolibriOS-Mod,代码行数:78,代码来源:osunixxf.c

示例13: waiter_main

static int waiter_main(int argc, char *argv[])
{
  sigset_t set;
  struct sigaction act;
  struct sigaction oact;
  int status;

  printf("waiter_main: Waiter started\n" );

  printf("waiter_main: Unmasking signal %d\n" , WAKEUP_SIGNAL);
  (void)sigemptyset(&set);
  (void)sigaddset(&set, WAKEUP_SIGNAL);
  status = sigprocmask(SIG_UNBLOCK, &set, NULL);
  if (status != OK)
    {
      printf("waiter_main: ERROR sigprocmask failed, status=%d\n",
              status);
    }

  printf("waiter_main: Registering signal handler\n" );
  act.sa_sigaction = wakeup_action;
  act.sa_flags  = SA_SIGINFO;

  (void)sigfillset(&act.sa_mask);
  (void)sigdelset(&act.sa_mask, WAKEUP_SIGNAL);

  status = sigaction(WAKEUP_SIGNAL, &act, &oact);
  if (status != OK)
    {
      printf("waiter_main: ERROR sigaction failed, status=%d\n" , status);
    }

#ifndef SDCC
  printf("waiter_main: oact.sigaction=%p oact.sa_flags=%x oact.sa_mask=%x\n",
          oact.sa_sigaction, oact.sa_flags, oact.sa_mask);
#endif

  /* Take the semaphore */

  printf("waiter_main: Waiting on semaphore\n" );
  FFLUSH();

  status = sem_wait(&sem);
  if (status != 0)
    {
      int error = errno;
      if (error == EINTR)
        {
          printf("waiter_main: sem_wait() successfully interrupted by signal\n" );
        }
      else
        {
          printf("waiter_main: ERROR sem_wait failed, errno=%d\n" , error);
        }
    }
  else
    {
      printf("waiter_main: ERROR awakened with no error!\n" );
    }

  /* Detach the signal handler */

  act.sa_handler = SIG_DFL;
  (void)sigaction(WAKEUP_SIGNAL, &act, &oact);

  printf("waiter_main: done\n" );
  FFLUSH();

  threadexited = true;
  return 0;
}
开发者ID:hll4fork,项目名称:nuttx-apps,代码行数:71,代码来源:sighand.c

示例14: main

int main(int argc, const char *argv[]) {
	int launchErr = 0;
	
	if (argc != 2)
		launchErr = 1;
	
	if (!launchErr)
		if ( !(_max_number = atoi(argv[1])) )
			launchErr = 1;
	
	if (launchErr) {
		char progname[512];
		strcpy(progname, argv[0]);
		
		printf("Usage: %s highest_number\n", basename(progname));
		
		return 0;
	}
	
	if (create_shared_memory_region(_max_number)) {
		printf("Error while creating the shared memory region.\n");
		
		return EXIT_FAILURE;
	}
	
	sem_t *semaphore = sem_open(SEM1_NAME, O_CREAT, 0600, NULL);
	
	if (semaphore == SEM_FAILED) {
		printf("An error has occoured while creating a semaphore.\n");
		
		return EXIT_FAILURE;
	}
	
	pthread_t main_tid;
	
	pthread_create(&main_tid, NULL, main_thread, NULL);
	
	sem_wait(semaphore);
	
	if (sem_close(semaphore))
		printf("An error has occoured while closing the semaphore. Continuing anyway...");
	
	unsigned int *sharedQueue;
	
	if (get_shared_memory_region(&sharedQueue)) {
		printf("Error while accessing the shared memory region.\n");
		
		exit(EXIT_FAILURE);
	}
	
	unsigned int count = sharedQueue[0];
	
	sharedQueue[0] = 0;
	
	qsort(sharedQueue, count, sizeof(unsigned int), cq_compare);
	 
	printf("Prime Numbers up to %d (%d): ", _max_number, count);
	
	unsigned int i;
	
	for (i = 1; i < count; i++)
		printf("%d ", sharedQueue[i]);
	
	printf("\n");
	
	if (shm_unlink(SHM1_NAME)) {
		printf("An error has occoured while closing the shared memory region.");
		
		return EXIT_FAILURE;
	}
	
	return EXIT_SUCCESS;
}
开发者ID:joaodealmeida,项目名称:SOPE2,代码行数:73,代码来源:main.c

示例15: com_android_nfc_NativeNfcSecureElement_doDisconnect

static jboolean com_android_nfc_NativeNfcSecureElement_doDisconnect(JNIEnv *e, jobject o, jint handle)
{
   jclass cls;
   jfieldID f;
   NFCSTATUS status;
   jboolean result = JNI_FALSE;
   phLibNfc_SE_List_t SE_List[PHLIBNFC_MAXNO_OF_SE];
   uint8_t i, No_SE = PHLIBNFC_MAXNO_OF_SE, SmartMX_index=0, SmartMX_detected = 0;
   uint32_t SmartMX_Handle;
   struct nfc_jni_callback_data cb_data;
   phNfc_sData_t    InParam;
   phNfc_sData_t    OutParam;
   uint8_t          Output_Buff[10];
   uint8_t          GpioGetValue[3] = {0x00, 0xF8, 0x2B};
   uint8_t          GpioSetValue[4];
   uint8_t          gpioValue;

   /* Create the local semaphore */
   if (!nfc_cb_data_init(&cb_data, NULL))
   {
      goto clean_and_return;
   }

   TRACE("Close Secure element function ");

   CONCURRENCY_LOCK();
   /* Disconnect */
   TRACE("Disconnecting from SMX (handle = 0x%x)", handle);
   REENTRANCE_LOCK();
   status = phLibNfc_RemoteDev_Disconnect(handle, 
                                          NFC_SMARTMX_RELEASE,
                                          com_android_nfc_jni_disconnect_callback,
                                          (void *)&cb_data);
   REENTRANCE_UNLOCK();
   if(status != NFCSTATUS_PENDING)
   {
      LOGE("phLibNfc_RemoteDev_Disconnect(SMX) returned 0x%04x[%s]", status, nfc_jni_get_status_name(status));
      goto clean_and_return;
   }
   TRACE("phLibNfc_RemoteDev_Disconnect(SMX) returned 0x%04x[%s]", status, nfc_jni_get_status_name(status));

   /* Wait for callback response */
   if(sem_wait(&cb_data.sem))
   {
       goto clean_and_return;
   }

   /* Disconnect Status */
   if(cb_data.status != NFCSTATUS_SUCCESS)
   {
     LOGE("\n> Disconnect SE ERROR \n" );
      goto clean_and_return;
   }
   CONCURRENCY_UNLOCK();

   /* Get GPIO information */
   CONCURRENCY_LOCK();
   InParam.buffer = GpioGetValue;
   InParam.length = 3;
   OutParam.buffer = Output_Buff;
   TRACE("phLibNfc_Mgt_IoCtl()- GPIO Get Value");
   REENTRANCE_LOCK();
   status = phLibNfc_Mgt_IoCtl(gHWRef,NFC_MEM_READ,&InParam, &OutParam,com_android_nfc_jni_ioctl_callback, (void *)&cb_data);
   REENTRANCE_UNLOCK();
   if(status!=NFCSTATUS_PENDING)
   {
       LOGE("IOCTL status error");
       goto clean_and_return;
   }

   /* Wait for callback response */
   if(sem_wait(&cb_data.sem))
   {
      LOGE("IOCTL semaphore error");
      goto clean_and_return;
   }

   if(cb_data.status != NFCSTATUS_SUCCESS)
   {
      LOGE("READ MEM ERROR");
      goto clean_and_return;
   }

   gpioValue = com_android_nfc_jni_ioctl_buffer->buffer[0];
   TRACE("GpioValue = Ox%02x",gpioValue);

   /* Set GPIO information */
   GpioSetValue[0] = 0x00;
   GpioSetValue[1] = 0xF8;
   GpioSetValue[2] = 0x2B;
   GpioSetValue[3] = (gpioValue & 0xBF);

   TRACE("GpioValue to be set = Ox%02x",GpioSetValue[3]);

   for(i=0;i<4;i++)
   {
       TRACE("0x%02x",GpioSetValue[i]);
   }

   InParam.buffer = GpioSetValue;
//.........这里部分代码省略.........
开发者ID:qingyue,项目名称:platform_packages,代码行数:101,代码来源:com_android_nfc_NativeNfcSecureElement.cpp


注:本文中的sem_wait函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。