Mail* Mailbox::Pend() { sem_wait(&semInside); Mail* mail = mailBuffer.front(); mailBuffer.pop(); return mail; }
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); int messagelen; char message[100]; //Prepares message to be delivered to controllers sprintf(message,"%d %d" , SHUTDOWN, SHUTDOWN); messagelen=strlen(message)+1; //Writes SHUTDOWN command to the controllers' fifos write(fdN,message,messagelen); write(fdS,message,messagelen); write(fdE,message,messagelen); write(fdW,message,messagelen); //Unlocks sem_post(semaphore); printf("Park Closed\n"); pthread_exit(NULL); return 0; }
// 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); }
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"); sleep(2); } tempoExec = tempoExec - 100; emExecucao = Remove(emExecucao); if(tempoExec > 0){ trataInterrupcao(1); }else{ trataInterrupcao(3); } break; } } executando=0; sem_post(&semEscalonador); } sem_post(&semEscalonador); }
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"); }
int main() { int *BufferA; int *BufferB; char c1, c2, c3; int bufAFilled, bufAEmpty, bufBFilled, bufBEmpty; int semX, semY, semZ, CSX, CSY, CSZ; int pX, pY; char *arg[1] = {0}; int shmid1, shmid2; int temp, loop_finished, counter, input; // Create semaphore bufAFilled bufAFilled = sem_create(500001, 0); if (bufAFilled < 0) { Error(1); // Error has occurred } // Create semaphore bufAEmpty bufAEmpty = sem_create(500002, 11); if (bufAEmpty < 0) { Error(1); // Error has occurred } // Create semaphore bufBFilled bufBFilled = sem_create(500003, 0); if (bufBFilled < 0) { Error(1); // Error has occurred } // Create semaphore bufBEmpty bufBEmpty = sem_create(500004, 23); if (bufBEmpty < 0) { Error(1); // Error has occurred } // Create semaphore semX semX = sem_create(500005, 0); if (semX < 0) { Error(1); // Error has occurred } // Create semaphore semY semY = sem_create(500006, 0); if (semY < 0) { Error(1); // Error has occurred } // Create semaphore semZ semZ = sem_create(500007, 0); if (semZ < 0) { Error(1); // Error has occurred } // Create semaphore CSX CSX = sem_create(500008, 0); if (CSX < 0) { Error(1); // Error has occurred } // Create semaphore CSY CSY = sem_create(500009, 0); if (CSY < 0) { Error(1); // Error has occurred } // Create semaphore CSZ CSZ = sem_create(500010, 0); if (CSZ < 0) { 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]; c3 = BufferB[input*3+2]; printf("+ %c%c%c +", c1, c2, c3); temp = sem_signal(bufBEmpty); if ((counter % 160) == 0) // Sleep after taking every 160 items { // printf("-!Sleeping 3 seconds!-"); // sleep(3); } counter++; // Signal the commencement of the filling both the buffers temp = sem_signal(CSX); temp = sem_signal(CSY); } // Synchronize with ProcX and ProcY temp = sem_signal(semX); temp = sem_signal(semY); temp = sem_wait(semZ); temp = sem_wait(semZ); // sleep(7); printf("\n"); // Remove semaphores temp = sem_rm(bufAEmpty); temp = sem_rm(bufAFilled); temp = sem_rm(bufBEmpty); temp = sem_rm(bufBFilled); temp = sem_rm(semX); temp = sem_rm(semY); temp = sem_rm(semZ); temp = sem_rm(CSX); temp = sem_rm(CSY); temp = sem_rm(CSZ); // Remove shared memory temp = shm_rm(shmid1); temp = shm_rm(shmid2); printf("\nProcZ: Exiting...\n"); return 1; }
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; }
int s_lock(struct slock *sp){ return sem_wait(sp->semp); }
void wait() { fprintf(stderr, "NandSim::wait for semaphore\n"); sem_wait(&sem); }
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; /* signal the other process we're almost done */ if (write(3, &rv, 4) != 4) errx(1, "magic write failed"); { char *nfsargv[] = { __UNCONST("nfsd"), NULL }; nfsd_main(1, nfsargv); } /*NOTREACHED*/ return 0; }
void begin_write(struct lectred* l) { sem_wait(&(l->ecriture)); }
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); }
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; }
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; }
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; InParam.length = 4; OutParam.buffer = Output_Buff; TRACE("phLibNfc_Mgt_IoCtl()- GPIO Set Value"); REENTRANCE_LOCK(); status = phLibNfc_Mgt_IoCtl(gHWRef,NFC_MEM_WRITE,&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; } result = JNI_TRUE; clean_and_return: CONCURRENCY_UNLOCK(); return result; }
int main (int argc, char *argv[]) { printf( "=============================================================================\n"); printf( "\nOperations on a semaphore.\n%ld iterations\n\n", ITERATIONS); printf( "%-45s %15s %15s\n", "Test", "Total(msec)", "average(usec)"); printf( "-----------------------------------------------------------------------------\n"); /* * Time the loop overhead so we can subtract it from the actual test times. */ TESTSTART assert(1 == one); TESTSTOP durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; overHeadMilliSecs = durationMilliSecs; /* * Now we can start the actual tests */ assert((w32sema = CreateSemaphore(NULL, (long) 0, (long) ITERATIONS, NULL)) != 0); TESTSTART assert((ReleaseSemaphore(w32sema, 1, NULL),1) == one); TESTSTOP assert(CloseHandle(w32sema) != 0); reportTest("W32 Post with no waiters"); assert((w32sema = CreateSemaphore(NULL, (long) ITERATIONS, (long) ITERATIONS, NULL)) != 0); TESTSTART assert((WaitForSingleObject(w32sema, INFINITE),1) == one); TESTSTOP assert(CloseHandle(w32sema) != 0); reportTest("W32 Wait without blocking"); assert(sem_init(&sema, 0, 0) == 0); TESTSTART assert((sem_post(&sema),1) == one); TESTSTOP assert(sem_destroy(&sema) == 0); reportTest("POSIX Post with no waiters"); assert(sem_init(&sema, 0, ITERATIONS) == 0); TESTSTART assert((sem_wait(&sema),1) == one); TESTSTOP assert(sem_destroy(&sema) == 0); reportTest("POSIX Wait without blocking"); printf( "=============================================================================\n"); /* * End of tests. */ return 0; }
static jbyteArray com_android_nfc_NativeNfcSecureElement_doTransceive(JNIEnv *e, jobject o,jint handle, jbyteArray data) { uint8_t offset = 0; uint8_t *buf; uint32_t buflen; phLibNfc_sTransceiveInfo_t transceive_info; jbyteArray result = NULL; int res; int tech = SecureElementTech; NFCSTATUS status; struct nfc_jni_callback_data cb_data; /* Create the local semaphore */ if (!nfc_cb_data_init(&cb_data, NULL)) { goto clean_and_return; } TRACE("Exchange APDU function "); CONCURRENCY_LOCK(); TRACE("Secure Element tech: %d\n", tech); buf = (uint8_t *)e->GetByteArrayElements(data, NULL); buflen = (uint32_t)e->GetArrayLength(data); /* Prepare transceive info structure */ if(tech == TARGET_TYPE_MIFARE_CLASSIC || tech == TARGET_TYPE_MIFARE_UL) { offset = 2; transceive_info.cmd.MfCmd = (phNfc_eMifareCmdList_t)buf[0]; transceive_info.addr = (uint8_t)buf[1]; } else if(tech == TARGET_TYPE_ISO14443_4) { transceive_info.cmd.Iso144434Cmd = phNfc_eIso14443_4_Raw; transceive_info.addr = 0; } transceive_info.sSendData.buffer = buf + offset; transceive_info.sSendData.length = buflen - offset; transceive_info.sRecvData.buffer = (uint8_t*)malloc(1024); transceive_info.sRecvData.length = 1024; if(transceive_info.sRecvData.buffer == NULL) { goto clean_and_return; } TRACE("phLibNfc_RemoteDev_Transceive(SMX)"); REENTRANCE_LOCK(); status = phLibNfc_RemoteDev_Transceive(handle, &transceive_info, com_android_nfc_jni_transceive_callback, (void *)&cb_data); REENTRANCE_UNLOCK(); if(status != NFCSTATUS_PENDING) { LOGE("phLibNfc_RemoteDev_Transceive(SMX) returned 0x%04x[%s]", status, nfc_jni_get_status_name(status)); goto clean_and_return; } TRACE("phLibNfc_RemoteDev_Transceive(SMX) returned 0x%04x[%s]", status, nfc_jni_get_status_name(status)); /* Wait for callback response */ if(sem_wait(&cb_data.sem)) { LOGE("TRANSCEIVE semaphore error"); goto clean_and_return; } if(cb_data.status != NFCSTATUS_SUCCESS) { LOGE("TRANSCEIVE error"); goto clean_and_return; } /* Copy results back to Java */ result = e->NewByteArray(com_android_nfc_jni_transceive_buffer->length); if(result != NULL) { e->SetByteArrayRegion(result, 0, com_android_nfc_jni_transceive_buffer->length, (jbyte *)com_android_nfc_jni_transceive_buffer->buffer); } clean_and_return: if(transceive_info.sRecvData.buffer != NULL) { free(transceive_info.sRecvData.buffer); } e->ReleaseByteArrayElements(data, (jbyte *)transceive_info.sSendData.buffer, JNI_ABORT); CONCURRENCY_UNLOCK(); return result; }
static void wait_main() { do { sem_wait(&thread_sem); } while(0); }
static int rping_test_server(struct rping_cb *cb) { struct ibv_send_wr *bad_wr; int ret; while (1) { /* Wait for client's Start STAG/TO/Len */ sem_wait(&cb->sem); if (cb->state != RDMA_READ_ADV) { fprintf(stderr, "wait for RDMA_READ_ADV state %d\n", cb->state); ret = -1; break; } DEBUG_LOG("server received sink adv\n"); /* Issue RDMA Read. */ cb->rdma_sq_wr.opcode = IBV_WR_RDMA_READ; cb->rdma_sq_wr.wr.rdma.rkey = cb->remote_rkey; cb->rdma_sq_wr.wr.rdma.remote_addr = cb->remote_addr; cb->rdma_sq_wr.sg_list->length = cb->remote_len; ret = ibv_post_send(cb->qp, &cb->rdma_sq_wr, &bad_wr); if (ret) { fprintf(stderr, "post send error %d\n", ret); break; } DEBUG_LOG("server posted rdma read req \n"); /* Wait for read completion */ sem_wait(&cb->sem); if (cb->state != RDMA_READ_COMPLETE) { fprintf(stderr, "wait for RDMA_READ_COMPLETE state %d\n", cb->state); ret = -1; break; } DEBUG_LOG("server received read complete\n"); /* Display data in recv buf */ if (cb->verbose) printf("server ping data: %s\n", cb->rdma_buf); /* Tell client to continue */ ret = ibv_post_send(cb->qp, &cb->sq_wr, &bad_wr); if (ret) { fprintf(stderr, "post send error %d\n", ret); break; } DEBUG_LOG("server posted go ahead\n"); /* Wait for client's RDMA STAG/TO/Len */ 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; } DEBUG_LOG("server received sink adv\n"); /* RDMA Write echo data */ cb->rdma_sq_wr.opcode = IBV_WR_RDMA_WRITE; cb->rdma_sq_wr.wr.rdma.rkey = cb->remote_rkey; cb->rdma_sq_wr.wr.rdma.remote_addr = cb->remote_addr; cb->rdma_sq_wr.sg_list->length = strlen(cb->rdma_buf) + 1; DEBUG_LOG("rdma write from lkey %x laddr %" PRIx64 " len %d\n", cb->rdma_sq_wr.sg_list->lkey, cb->rdma_sq_wr.sg_list->addr, cb->rdma_sq_wr.sg_list->length); ret = ibv_post_send(cb->qp, &cb->rdma_sq_wr, &bad_wr); if (ret) { fprintf(stderr, "post send error %d\n", ret); break; } /* Wait for completion */ ret = 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; } DEBUG_LOG("server rdma write complete \n"); /* Tell client to begin again */ ret = ibv_post_send(cb->qp, &cb->sq_wr, &bad_wr); if (ret) { fprintf(stderr, "post send error %d\n", ret); break; } DEBUG_LOG("server posted go ahead\n"); } return ret; }
static void wait_thread() { do { sem_wait(&main_sem); } while(0); }
void fill_any_dir( grid_t *grid, piece_list_t *piece_list, int start_col, int start_row, int inc_index ) { int j; int found; int row, col; int col_inc[] = {1, 0, -1, 0}; int row_inc[] = {0, 1, 0, -1}; int count; row = start_row; col = start_col; /* Loop through the entire column / row and stop when we hit an edge or a puzzle grid cell that is already filled in. */ while ((row >= 0) && (col >= 0) && (row < grid->numrows) && (col < grid->numcols)) { // Wait for piece to unlock and then solve it if not solved sem_wait(&grid->cells[col][row].threadLock); // If solved skip and unlock, else solve if (grid->cells[col][row].piece == NULL) { /* Ensure that we're ready for the piece by making sure that at least two tabs are defined. */ count = 0; if (grid->cells[col][row].north != NO_PIECE_INDEX) count++; if (grid->cells[col][row].west != NO_PIECE_INDEX) count++; if (grid->cells[col][row + 1].north != NO_PIECE_INDEX) count++; if (grid->cells[col + 1][row].west != NO_PIECE_INDEX) count++; if (count >= 2) { /* Search the set of pieces for what will go in this grid position. */ found = NO_PIECE_INDEX; for (j = 0; (j < grid->numcols * grid->numrows) && (found == NO_PIECE_INDEX); j++) { /* I will find the first piece whose tabs match the defined tabs of the grid cell. This will find the unique pieces _if_ the grid cell has at least two adjacent tabs that are not -1. */ if ( ((grid->cells[col][row].north == NO_PIECE_INDEX) || (grid->cells[col][row].north == piece_list->pieces[j].tab[NORTH_TAB])) && ((grid->cells[col + 1][row].west == NO_PIECE_INDEX) || (grid->cells[col + 1][row].west == piece_list->pieces[j].tab[EAST_TAB])) && ((grid->cells[col][row + 1].north == NO_PIECE_INDEX) || (grid->cells[col][row + 1].north == piece_list->pieces[j].tab[SOUTH_TAB])) && ((grid->cells[col][row].west == NO_PIECE_INDEX) || (grid->cells[col][row].west == piece_list->pieces[j].tab[WEST_TAB])) ) { found = j; } } /* When we get the piece, fit it into the grid and update the tabs of the grid for all surrounding grid cells. */ if (found != NO_PIECE_INDEX) { grid->cells[col][row].piece = &(piece_list->pieces[found]); grid->cells[col][row].north = piece_list->pieces[found].tab[NORTH_TAB]; grid->cells[col + 1][row].west = piece_list->pieces[found].tab[EAST_TAB]; grid->cells[col][row + 1].north = piece_list->pieces[found].tab[SOUTH_TAB]; grid->cells[col][row].west = piece_list->pieces[found].tab[WEST_TAB]; } else { printf("Error piece not found!!!\n"); } } // Unlock after solving the piece sem_post(&grid->cells[col][row].threadLock); } // Unlock if piece is solved after getting access to the critical section else { sem_post(&grid->cells[col][row].threadLock); } /* Go to the next grid cell in the direction given as a parameter. */ row += row_inc[inc_index]; col += col_inc[inc_index]; } }
int nximage_main(int argc, char *argv[]) { nxgl_mxpixel_t color; int ret; /* Initialize NX */ ret = nximage_initialize(); message("nximage_main: NX handle=%p\n", g_nximage.hnx); if (!g_nximage.hnx || ret < 0) { message("nximage_main: Failed to get NX handle: %d\n", errno); g_nximage.code = NXEXIT_NXOPEN; goto errout; } /* Set the background to the configured background color */ color = nximage_bgcolor(); message("nximage_main: Set background color=%d\n", color); ret = nx_setbgcolor(g_nximage.hnx, &color); if (ret < 0) { message("nximage_main: nx_setbgcolor failed: %d\n", errno); g_nximage.code = NXEXIT_NXSETBGCOLOR; goto errout_with_nx; } /* Get the background window */ ret = nx_requestbkgd(g_nximage.hnx, &g_nximagecb, NULL); if (ret < 0) { message("nximage_main: nx_setbgcolor failed: %d\n", errno); g_nximage.code = NXEXIT_NXREQUESTBKGD; goto errout_with_nx; } /* Wait until we have the screen resolution. We'll have this immediately * unless we are dealing with the NX server. */ while (!g_nximage.havepos) { (void)sem_wait(&g_nximage.sem); } message("nximage_main: Screen resolution (%d,%d)\n", g_nximage.xres, g_nximage.yres); /* Now, put up the NuttX logo and wait a bit so that it visible. */ nximage_image(g_nximage.hbkgd); sleep(5); /* Release background */ (void)nx_releasebkgd(g_nximage.hbkgd); /* Close NX */ errout_with_nx: message("nximage_main: Close NX\n"); nx_close(g_nximage.hnx); errout: return g_nximage.code; }
void *MavlinkStatusTask(void *ptr) { MavlinkStruct *Mavlink = (MavlinkStruct *) ptr; AttitudeData *AttitudeDesire = Control.AttitudeDesire; AttitudeData *AttitudeMesure = Mavlink->AttitudeMesure; AttData Data, Speed; AttData DataD, SpeedD; AttData DataM, SpeedM; double Error[4] = {0.0, 0.0, 0.0, 0.0}; uint32_t TimeStamp; mavlink_message_t msg; uint16_t len; uint8_t buf[BUFFER_LENGTH]; int bytes_sent; uint32_t sensor = 0xf00f; printf("%s : Mavlink Status démarré\n", __FUNCTION__); pthread_barrier_wait(&(MavlinkStartBarrier)); while (MavlinkActivated) { sem_wait(&MavlinkStatusTimerSem); if (MavlinkActivated == 0) break; memset(buf, 0, BUFFER_LENGTH); pthread_spin_lock(&(AttitudeMesure->AttitudeLock)); memcpy((void *) &Data, (void *) &(AttitudeMesure->Data), sizeof(AttData)); memcpy((void *) &Speed, (void *) &(AttitudeMesure->Speed), sizeof(AttData)); TimeStamp = AttitudeMesure->timestamp_s*1000 + AttitudeMesure->timestamp_n/1000000L; pthread_spin_unlock(&(AttitudeMesure->AttitudeLock)); //Send Heartbeat mavlink_msg_heartbeat_pack(SYSTEM_ID, COMPONENT_ID, &msg, MAV_TYPE_HELICOPTER, MAV_AUTOPILOT_GENERIC, MAV_MODE_GUIDED_ARMED, 0, MAV_STATE_ACTIVE); len = mavlink_msg_to_send_buffer(buf, &msg); bytes_sent = sendto(Mavlink->sock, buf, len, 0, (struct sockaddr *)&Mavlink->gcAddr, sizeof(struct sockaddr_in)); // Send Status mavlink_msg_sys_status_pack(SYSTEM_ID, COMPONENT_ID, &msg, sensor, sensor, 0, 500, 11000, -1, -1, 0, 0, 0, 0, 0, 0); len = mavlink_msg_to_send_buffer(buf, &msg); bytes_sent = sendto(Mavlink->sock, buf, len, 0, (struct sockaddr *)&Mavlink->gcAddr, sizeof (struct sockaddr_in)); // Send Local Position mavlink_msg_local_position_ned_pack(SYSTEM_ID, COMPONENT_ID, &msg, TimeStamp, 0, 0, (float) Data.Elevation, 0, 0, (float) Speed.Elevation); len = mavlink_msg_to_send_buffer(buf, &msg); bytes_sent = sendto(Mavlink->sock, buf, len, 0, (struct sockaddr *)&Mavlink->gcAddr, sizeof(struct sockaddr_in)); pthread_spin_lock(&(AttitudeDesire->AttitudeLock)); memcpy((void *) &DataD, (void *) &(AttitudeDesire->Data), sizeof(AttData)); memcpy((void *) &SpeedD, (void *) &(AttitudeDesire->Speed), sizeof(AttData)); pthread_spin_unlock(&(AttitudeDesire->AttitudeLock)); pthread_spin_lock(&(AttitudeMesure->AttitudeLock)); memcpy((void *) &DataM, (void *) &(AttitudeMesure->Data), sizeof(AttData)); memcpy((void *) &SpeedM, (void *) &(AttitudeMesure->Speed), sizeof(AttData)); pthread_spin_unlock(&(AttitudeMesure->AttitudeLock)); Error[HEIGHT] = DataD.Elevation - DataM.Elevation; Error[ROLL] = DataD.Roll - DataM.Roll; Error[PITCH] = DataD.Pitch - DataM.Pitch; Error[YAW] = DataD.Yaw - DataM.Yaw; // Send Attitude mavlink_msg_attitude_pack(SYSTEM_ID, COMPONENT_ID, &msg, TimeStamp, (float) Data.Roll, (float) Data.Pitch, (float) Data.Yaw, (float) Speed.Roll, (float) Speed.Pitch, (float) Speed.Yaw); len = mavlink_msg_to_send_buffer(buf, &msg); bytes_sent = sendto(Mavlink->sock, buf, len, 0, (struct sockaddr *)&Mavlink->gcAddr, sizeof(struct sockaddr_in)); } printf("%s : Mavlink Status Arrêté\n", __FUNCTION__); pthread_exit(NULL); }
void * _dispatcher_worker_run(void * arg) { int child_count = 0; int child_status; pid_t fork_child_pid, wait_child_pid; dispatcher_worker_info * worker_info = arg; Dispatcher * self = worker_info->dispatcher; // Build epoll set int epollfd = _dispatcher_build_listener_epoll_set(self); struct epoll_event events[10]; while (1) { int ready_fds; if (self->_worker_model == DISPATCHER_WORKER_MODEL_POSTFORK) { // Naively clean up after children wait_child_pid = waitpid(-1, &child_status, WNOHANG); if (wait_child_pid > 0) { child_count--; } } // Look for sockets that are ready for action // Block on the semaphore sem_wait(worker_info->poll_sem); ready_fds = _dispatcher_poll_listeners(self, epollfd, events, 10); if (ready_fds <= 0) { // Release the semaphore sem_post(worker_info->poll_sem); continue; } // Figure out which listeners are ready int found_fd; for (int i = 0; i < ready_fds; i++) { found_fd = 0; for (int j = 0; j < self->_listener_count; j++) { dispatcher_listener * tmp_listener = self->_listeners[j]; if (tmp_listener->sock->socket == events[i].data.fd) { dispatcher_callback_info cb_info = { self, tmp_listener->sock, {}, 0, tmp_listener->cbarg }; if (tmp_listener->poll_callback(&cb_info)) { // Something went wrong in the poll_callback sem_post(worker_info->poll_sem); break; } // Release the semaphore sem_post(worker_info->poll_sem); if (self->_worker_model == DISPATCHER_WORKER_MODEL_POSTFORK) { // fork it fork_child_pid = fork(); if (fork_child_pid > 0) { // Parent cb_info.extra_flag = 1; tmp_listener->cleanup_callback(&cb_info); printf("[%d] forked off child with PID %d\n", getpid(), fork_child_pid); child_count++; break; } else { // Child worker_info->worker_num = child_count; } } // printf("[%d] Handling request in worker %d\n", getpid(), worker_info->worker_num); tmp_listener->run_callback(&cb_info); tmp_listener->cleanup_callback(&cb_info); if (self->_worker_model == DISPATCHER_WORKER_MODEL_POSTFORK && fork_child_pid == 0) { // Child printf("[%d] Calling _exit() in child\n", getpid()); _exit(0); } found_fd = 1; break; } } if (found_fd) { // Go back to the top loop if we handled a request break; } } // Release the semaphore if we didn't find anything sem_post(worker_info->poll_sem); } return NULL; }
void *POSIX_Init( void *argument ) { int status; int value; int i; sem_t sems[MAX_SEMS]; sem_t sem2; sem_t *n_sem1; sem_t *n_sem2; struct timespec waittime; char failure_msg[80]; puts( "\n\n*** POSIX SEMAPHORE MANAGER TEST 1 ***" ); puts( "Init: sem_init - UNSUCCESSFUL (EINVAL)" ); status = sem_init(NULL, 0, 1); fatal_posix_service_status( status, -1, "sem_init error return status"); fatal_posix_service_status( errno, EINVAL, "sem_init errorno EINVAL" ); puts( "Init: sem_init - SUCCESSFUL" ); for (i = 0; i < MAX_SEMS; i++) { status = sem_init(&sems[i], 0, i); sprintf(failure_msg, "sem_init %d", i ); fatal_posix_service_status( status, 0, failure_msg); } puts( "Init: sem_init - UNSUCCESSFUL (ENOSPC)" ); status = sem_init(&sem2, 0, 1); fatal_posix_service_status( status, -1, "sem_init error return status"); fatal_posix_service_status( errno, ENOSPC, "sem_init errorno ENOSPC" ); puts( "Init: sem_init - UNSUCCESSFUL (ENOSYS -- pshared not supported)" ); status = sem_init(&sem2, 1, 1); fatal_posix_service_status( status, -1, "sem_init error return status"); fatal_posix_service_status( errno, ENOSYS, "sem_init errno set to ENOSYS"); puts( "Init: sem_getvalue - SUCCESSFUL "); for (i = 0; i < MAX_SEMS; i++) { status = sem_getvalue(&sems[i], &value); sprintf( failure_msg, "sem_getvalue %d", i ); fatal_posix_service_status( status, 0, failure_msg ); fatal_posix_service_status( value, i, "sem_getvalue correct value" ); } puts( "Init: sem_getvalue - UNSUCCESSFUL "); status = sem_getvalue(&sem2, &value); fatal_posix_service_status( status, -1, "sem_getvalue error return status"); fatal_posix_service_status( errno, EINVAL, "sem_getvalue errno EINVAL"); puts( "Init: sem_destroy - SUCCESSFUL" ); status = sem_destroy(&sems[0]); fatal_posix_service_status( status, 0, "sem_destroy semaphore 0"); puts( "Init: sem_destroy - UNSUCCESSFUL (EINVAL)" ); status = sem_destroy(&sem2); fatal_posix_service_status( status, -1, "sem_destroy error return status"); fatal_posix_service_status( errno, EINVAL, "sem_destroy errno EINVAL"); puts( "Init: sem_wait - SUCCESSFUL" ); status = sem_wait(&sems[1]); fatal_posix_service_status( status, 0, "sem_wait semaphore 1"); /* sem[1].count = 0 */ puts( "Init: sem_wait - UNSUCCESSFUL (EINVAL)" ); status = sem_wait(&sem2); fatal_posix_service_status( status, -1, "sem_wait error return status"); fatal_posix_service_status( errno, EINVAL, "sem_wait errno EINVAL"); puts( "Init: sem_post - SUCCESSFUL" ); status = sem_post(&sems[1]); fatal_posix_service_status( status, 0, "sem_post semaphore 1"); /* sem[1].count = 1 */ puts( "Init: sem_wait - SUCCESSFUL (after a sem_post)" ); status = sem_wait(&sems[1]); fatal_posix_service_status( status, 0, "sem_wait semaphore 1"); /* sem[1].count = 0 */ puts( "Init: sem_trywait - SUCCESSFUL" ); status = sem_trywait(&sems[2]); fatal_posix_service_status( status, 0, "sem_trywait semaphore 2"); /* sem[2].count = 1 */ puts( "Init: sem_trywait - UNSUCCESSFUL (EAGAIN)" ); status = sem_trywait(&sems[1]); fatal_posix_service_status( status, -1, "sem_trywait error return status"); fatal_posix_service_status( errno, EAGAIN, "sem_trywait errno EAGAIN"); /* sem[1].count = 0 */ puts( "Init: sem_trywait - UNSUCCESSFUL (EINVAL)" ); status = sem_trywait(&sem2); fatal_posix_service_status( status, -1, "sem_trywait error return status"); fatal_posix_service_status( errno, EINVAL, "sem_trywait errno EINVAL"); #if 0 status = sem_post(&sems[2]); fatal_posix_service_status( status, 0, "sem_post semaphore 2"); /* sem[2].count = 2 */ #else /* sem[2].count = 1 */ #endif puts( "Init: sem_timedwait - SUCCESSFUL" ); waittime.tv_sec = time(NULL) + 1; waittime.tv_nsec = 100; status = sem_timedwait(&sems[2], &waittime); fatal_posix_service_status( status, 0, "sem_timedwait semaphore 2"); /* sem[2].count = 0 */ puts( "Init: sem_timedwait - UNSUCCESSFUL (ETIMEDOUT)" ); status = sem_timedwait(&sems[2], &waittime); fatal_posix_service_status( status, -1, "sem_timedwait error return status"); fatal_posix_service_status( errno, ETIMEDOUT, "sem_timedwait errno ETIMEDOUT"); /* * To do this case, we must be blocking when we want the semaphore. * POSIX doesn't want you to check the error if you can get the resource. */ #if 1 puts( "Init: sem_timedwait - UNSUCCESSFUL (EINVAL) -- skipping" ); #else puts( "Init: sem_timedwait - UNSUCCESSFUL (EINVAL)" ); waittime.tv_sec = 0; waittime.tv_nsec = 0x7FFFFFFF; status = sem_timedwait(&sems[2], &waittime); fatal_posix_service_status( status, -1, "sem_timedwait error return status"); fatal_posix_service_status( errno, EINVAL, "sem_init errno EINVAL"); #endif puts( "Init: sem_post - UNSUCCESSFUL (EINVAL)" ); status = sem_post(&sem2); fatal_posix_service_status( status, -1, "sem_post error return status"); fatal_posix_service_status( errno, EINVAL, "sem_post errno EINVAL"); puts( "Init: sem_destroy - SUCCESSFUL" ); for (i = 1; i < MAX_SEMS; i++) { status = sem_destroy(&sems[i]); sprintf( failure_msg, "sem_destroy %d", i ); fatal_posix_service_status( status, 0, failure_msg ); } /* Modes are currently unsupported */ /* * Validate all sem_open return paths. */ puts( "Init: sem_open - UNSUCCESSFUL (ENAMETOOLONG)" ); n_sem1 = sem_open(Get_Too_Long_Name(), O_CREAT, 0777, 1 ); fatal_posix_sem( n_sem1, "sem_open error return status" ); fatal_posix_service_status( errno, ENAMETOOLONG, "sem_open errorno ENAMETOOLONG" ); puts( "Init: sem_open - sem1 SUCCESSFUL" ); n_sem1 = sem_open( "sem1",O_CREAT, 0777, 1 ); rtems_test_assert( n_sem1 != SEM_FAILED ); puts( "Init: sem_destroy - named sem1 - EINVAL" ); status = sem_destroy(n_sem1); fatal_posix_service_status( status, -1, "sem_destroy named semaphore"); fatal_posix_service_status( errno, EINVAL, "sem_destroy named semaphore"); puts( "Init: sem_open - Create an Existing sem (EEXIST)" ); n_sem2 = sem_open("sem1", O_CREAT | O_EXCL, 0777, 1); fatal_posix_sem( n_sem2, "sem_open error return status" ); fatal_posix_service_status( errno, EEXIST, "sem_open errno EEXIST"); puts( "Init: sem_open - Open new sem without create flag (ENOENT)" ); n_sem2 = sem_open("sem3", O_EXCL, 0777, 1); fatal_posix_sem( n_sem2, "sem_open error return status" ); fatal_posix_service_status( errno, ENOENT, "sem_open errno EEXIST"); /* * XXX - Could not hit the following errors: * E_POSIX_Semaphore_Create_support only fails if * ENOSYS - When semaphore is shared between processes. * ENOSPC - When out of memory. */ /* * Validate we can wait on a semaphore opened with sem_open. */ puts( "Init: sem_wait on sem1" ); status = sem_wait(n_sem1); fatal_posix_service_status( status, 0, "sem_wait opened semaphore"); /* * Validate a second open returns the same semaphore. */ puts( "Init: sem_open - Open an existing sem ( same id )" ); n_sem2 = sem_open("sem1", 0 ); rtems_test_assert( n_sem2 == n_sem1 ); /* * Unlink the semaphore, then verify an open of the same name produces a * different semaphore. */ puts( "Init: sem_unlink - sem1 SUCCESSFUL" ); status = sem_unlink( "sem1" ); fatal_posix_service_status( status, 0, "sem_unlink locked semaphore"); puts( "Init: sem_open - Reopen sem1 SUCCESSFUL with a different id" ); n_sem2 = sem_open( "sem1", O_CREAT | O_EXCL, 0777, 1); rtems_test_assert( n_sem2 != SEM_FAILED ); rtems_test_assert( n_sem2 != n_sem1 ); /* * Validate we can call close on a semaphore opened with sem_open. */ puts( "Init: sem_close (1) - SUCCESSFUL" ); status = sem_close( n_sem1 ); fatal_posix_service_status( status, 0, "sem_close semaphore"); /* * Validate it n_sem2 (the last open for sem1 name can be * correctly closed and unlinked. */ puts( "Init: sem_close (2) - SUCCESSFUL" ); status = sem_close( n_sem2 ); fatal_posix_service_status( status, 0, "sem_close semaphore"); puts( "Init: sem_unlink - sem1 (2) SUCCESSFUL" ); status = sem_unlink( "sem1" ); fatal_posix_service_status( status, 0, "sem_unlink locked semaphore"); puts( "Init: sem_close - UNSUCCESSFUL (EINVAL)" ); status = sem_close(n_sem2); fatal_posix_service_status( status, -1, "sem_close error return status"); fatal_posix_service_status( errno, EINVAL, "sem_close errno EINVAL"); puts( "Init: sem_unlink - UNSUCCESSFUL (ENOENT)" ); status = sem_unlink("sem1"); fatal_posix_service_status( status, -1, "sem_unlink error return status"); fatal_posix_service_status( errno, ENOENT, "sem_close errno EINVAL"); /* * Validate we can unlink (2) */ puts( "Init: sem_unlink (NULL) - EINVAL" ); status = sem_unlink( NULL ); fatal_posix_service_status( status, -1, "sem_unlink error return status"); fatal_posix_service_status( errno, EINVAL, "sem_unlink errno value"); puts( "Init: sem_unlink (\"\") - EINVAL" ); status = sem_unlink( "" ); fatal_posix_service_status( status, -1, "sem_unlink error return status"); fatal_posix_service_status( errno, EINVAL, "sem_unlink errno value"); /* * XXX - Cant' create location OBJECTS_ERROR or OBJECTS_REMOTE. * sem_close and sem_unlink. */ puts( "Init: sem_unlink - UNSUCCESSFUL (ENOENT)" ); status = sem_unlink("sem2"); fatal_posix_service_status( status, -1, "sem_unlink error return status"); fatal_posix_service_status( errno, ENOENT, "sem_unlink errno ENOENT"); rtems_test_assert( (status == -1) && (errno == ENOENT) ); /* Try adding in unlinking before closing... (can we still open?) */ puts( "*** END OF POSIX SEMAPHORE MANAGER TEST 1 ***" ); rtems_test_exit(0); return NULL; /* just so the compiler thinks we returned something */ }
/* Thread One calls this method to start blocking.... * * IT does **NOT** invoke clearWakeupAlreadyReceived() * * after it wakes up!!! This feature is exploited by Thread. */ status_t Semaphore::waitForSignal(BOOLEAN theWakeupCouldHaveAlreadyHappened /*= FALSE*/) { lock("Semaphore::waitForSignal"); if ( getIsThreadWaitingNoMutex() == TRUE ) { cerr << "[Semaphore:waitForSignal] Error: " << "Another thread is already waiting on this Semaphore." << endl; unlock("Semaphore::waitForSignal"); return FAILURE; } /* Has the wakeup call already been made? */ if ( theWakeupCouldHaveAlreadyHappened == TRUE ) { if ( getWakeupAlreadyReceivedNoMutex() == TRUE ) { setIsThreadWaitingNoMutex ( FALSE ); /* It is possible for a race condition to trigger a semaphore * multiple times while the sem_wait is running... * So lets detect that, and clean it up nicely... */ while ( sem_trywait ( & getSemaphoreDataNoMutex() ) == 0 ) { cerr << endl << "[Semaphore:waitForSignal(waited)] Warning: " << "Semaphore count was non-zero. Decrementing..." << endl << endl; } unlock("Semaphore::waitForSignal"); return SUCCESS; } } setIsThreadWaitingNoMutex ( TRUE ); unlock("Semaphore::waitForSignal"); /* sem_wait always returns 0 */ sem_wait ( & getSemaphoreDataNoMutex() ); /* It is possible for a race condition to trigger a semaphore * multiple times while the sem_wait is running... * So lets detect that, and clean it up nicely... */ while ( sem_trywait ( & getSemaphoreDataNoMutex() ) == 0 ) { cerr << endl << "[Semaphore:waitForSignal(waiting)] Warning: " << "Semaphore count was non-zero. Decrementing..." << endl << endl; } /* There is a rare race condtion wherein we resume running right * after the sem_post(), and before the other thread finishes * wakeupOtherThread(). This doesn't guarantee that wakeupOtherThread() * has finished, but it improves the odds, and insures that our Mutex * is unlocked when we return. * Discovered through race condition wherein main() exited right after * Thread::waitForThreadToStop() returned. */ lock("Semaphore::waitForSignal[2]"); /* As long as we are locked, this needs to be cleared... */ setIsThreadWaitingNoMutex ( FALSE ); unlock("Semaphore::waitForSignal[2]"); return SUCCESS; }
static boolean reset_user_passwd(SSL *ssl_client, boolean is_admin_flag) { char buffer[BUFFER_LENGTH + 1]; char token_name[TOKEN_NAME_LENGTH + 1]; char username[USER_NAME_LENGTH + 1]; MYSQL *db_conn = NULL; MYSQL_RES *result = NULL; MYSQL_ROW row; char stat[SQL_STATEMENT_LENGTH + 1]; char err_msg[ERR_MSG_LENGTH + 1]; unsigned int user_or_admin_id; char email_address[EMAIL_ADDRESS_LENGTH + 1]; char random_passwd[PASSWD_LENGTH + 1]; char random_salt_value[SALT_VALUE_LENGTH + 1]; char random_passwd_with_salt_value[PASSWD_LENGTH + SALT_VALUE_LENGTH + 1]; char salted_passwd_hash[SHA1_DIGEST_LENGTH + 1]; // Receive user/admin password resetting information if(SSL_recv_buffer(ssl_client, buffer, NULL) == 0) { fprintf(stderr, "Receiving user/admin password resetting information failed\n"); goto ERROR; } // Get a user/admin password resetting information token from buffer if(read_token_from_buffer(buffer, 1, token_name, username) != READ_TOKEN_SUCCESS || strcmp(token_name, "username") != 0) int_error("Extracting the username failed"); // Connect the database connect_db(&db_conn, DB_IP, DB_USERNAME, DB_PASSWD, DB_NAME); // Check for the existence of username if(is_admin_flag) { sprintf(stat, "SELECT admin_id, email_address FROM %s WHERE username LIKE '%s' COLLATE latin1_general_cs", ESA__ADMINS, username); } else { sprintf(stat, "SELECT user_id, email_address FROM %s WHERE username LIKE '%s' COLLATE latin1_general_cs", ESA__USERS, username); } if(mysql_query(db_conn, stat)) { sprintf(err_msg, "Error %u: %s\n", mysql_errno(db_conn), mysql_error(db_conn)); int_error(err_msg); } result = mysql_store_result(db_conn); row = mysql_fetch_row(result); // The user/admin does not exist if(!row) { // Send the user/admin password resetting result flag write_token_into_buffer("user_or_admin_passwd_resetting_result_flag", "0", true, buffer); write_token_into_buffer("error_msg", "User does not exist", false, buffer); if(!SSL_send_buffer(ssl_client, buffer, strlen(buffer))) { fprintf(stderr, "Sending the user/admin password resetting result flag failed\n"); goto ERROR; } goto ERROR; } user_or_admin_id = atoi(row[0]); strcpy(email_address, row[1]); if(result) { mysql_free_result(result); result = NULL; } // Generate a random 8 character password gen_random_password(random_passwd); // Generate a random 8 character salt value gen_random_salt_value(random_salt_value); // Get the salted password hash sprintf(random_passwd_with_salt_value, "%s%s", random_passwd, random_salt_value); sum_sha1_from_string(random_passwd_with_salt_value, strlen(random_passwd_with_salt_value), salted_passwd_hash, SALTED_PASSWD_HASH_PATH); // Update the password hash information if(is_admin_flag) { sprintf(stat, "UPDATE %s SET salted_passwd_hash = '%s', salt_value = '%s' WHERE admin_id = %u", ESA__ADMINS, salted_passwd_hash, random_salt_value, user_or_admin_id); } else { sprintf(stat, "UPDATE %s SET salted_passwd_hash = '%s', salt_value = '%s' WHERE user_id = %u", ESA__USERS, salted_passwd_hash, random_salt_value, user_or_admin_id); } if(mysql_query(db_conn, stat)) { sprintf(err_msg, "Error %u: %s\n", mysql_errno(db_conn), mysql_error(db_conn)); int_error(err_msg); } // Generate an SSL certificate generate_ssl_cert(db_conn, user_or_admin_id, username, is_admin_flag, random_passwd, email_address, SSL_CERT_PRIV_KEY_PATH, SSL_CERT_REQ_PATH, ENC_SSL_CERT_PATH, FULL_ENC_SSL_CERT_PATH, FULL_ENC_SSL_CERT_HASH_PATH); disconnect_db(&db_conn); // Lock an e-mail sending if(sem_wait(&email_sending_lock_mutex) != 0) int_error("Locking the mutex failed"); if(!send_passwd_to_user_email_address(email_address, username, is_admin_flag, random_passwd)) { // Send the user/admin password resetting result flag write_token_into_buffer("user_or_admin_passwd_resetting_result_flag", "0", true, buffer); write_token_into_buffer("error_msg", get_send_email_error_msg(), false, buffer); // Unlock an e-mail sending if(sem_post(&email_sending_lock_mutex) != 0) int_error("Unlocking the mutex failed"); if(!SSL_send_buffer(ssl_client, buffer, strlen(buffer))) { fprintf(stderr, "Sending the user/admin password resetting result flag failed\n"); goto ERROR; } goto ERROR; } // Unlock an e-mail sending if(sem_post(&email_sending_lock_mutex) != 0) int_error("Unlocking the mutex failed"); // Send the user/admin password resetting result flag write_token_into_buffer("user_or_admin_passwd_resetting_result_flag", "1", true, buffer); if(!SSL_send_buffer(ssl_client, buffer, strlen(buffer))) { fprintf(stderr, "Sending the user/admin password resetting result flag failed\n"); goto ERROR; } return true; ERROR: if(result) { mysql_free_result(result); result = NULL; } disconnect_db(&db_conn); return false; }
static jint com_android_nfc_NativeNfcSecureElement_doOpenSecureElementConnection(JNIEnv *e, jobject o) { NFCSTATUS ret; int semResult; 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; phLibNfc_sADD_Cfg_t discovery_cfg; phLibNfc_Registry_Info_t registry_info; phNfc_sData_t InParam; phNfc_sData_t OutParam; uint8_t ExternalRFDetected[3] = {0x00, 0xFC, 0x01}; uint8_t GpioGetValue[3] = {0x00, 0xF8, 0x2B}; uint8_t GpioSetValue[4]; uint8_t gpioValue; uint8_t Output_Buff[10]; uint8_t reg_value; uint8_t mask_value; struct nfc_jni_callback_data cb_data; /* Create the local semaphore */ if (!nfc_cb_data_init(&cb_data, NULL)) { goto clean_and_return; } /* Registery */ registry_info.MifareUL = TRUE; registry_info.MifareStd = TRUE; registry_info.ISO14443_4A = TRUE; registry_info.ISO14443_4B = TRUE; registry_info.Jewel = TRUE; registry_info.Felica = TRUE; registry_info.NFC = FALSE; CONCURRENCY_LOCK(); TRACE("Open Secure Element"); /* Test if External RF field is detected */ InParam.buffer = ExternalRFDetected; InParam.length = 3; OutParam.buffer = Output_Buff; TRACE("phLibNfc_Mgt_IoCtl()"); REENTRANCE_LOCK(); ret = phLibNfc_Mgt_IoCtl(gHWRef,NFC_MEM_READ,&InParam, &OutParam,com_android_nfc_jni_ioctl_callback, (void *)&cb_data); REENTRANCE_UNLOCK(); if(ret!=NFCSTATUS_PENDING) { LOGE("IOCTL status error"); } /* 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; } /* Check the value */ reg_value = com_android_nfc_jni_ioctl_buffer->buffer[0]; mask_value = reg_value & 0x40; if(mask_value == 0x40) { TRACE("External RF Field detected"); goto clean_and_return; } /* Get Secure Element List */ TRACE("phLibNfc_SE_GetSecureElementList()"); ret = phLibNfc_SE_GetSecureElementList( SE_List, &No_SE); if (ret == NFCSTATUS_SUCCESS) { TRACE("\n> Number of Secure Element(s) : %d\n", No_SE); /* Display Secure Element information */ for (i = 0; i<No_SE; i++) { if (SE_List[i].eSE_Type == phLibNfc_SE_Type_SmartMX) { TRACE("> SMX detected"); TRACE("> Secure Element Handle : %d\n", SE_List[i].hSecureElement); /* save SMARTMX index */ SmartMX_detected = 1; SmartMX_index = i; } } if(SmartMX_detected) { REENTRANCE_LOCK(); TRACE("phLibNfc_RemoteDev_NtfRegister()"); ret = phLibNfc_RemoteDev_NtfRegister(®istry_info, com_android_nfc_jni_open_secure_element_notification_callback, (void *)&cb_data); REENTRANCE_UNLOCK(); if(ret != NFCSTATUS_SUCCESS) { LOGE("Register Notification error"); goto clean_and_return; } /* Set wired mode */ REENTRANCE_LOCK(); TRACE("phLibNfc_SE_SetMode: Wired mode"); ret = phLibNfc_SE_SetMode( SE_List[SmartMX_index].hSecureElement, phLibNfc_SE_ActModeWired, com_android_nfc_jni_smartMX_setModeCb, (void *)&cb_data); REENTRANCE_UNLOCK(); if (ret != NFCSTATUS_PENDING ) { LOGE("\n> SE Set SmartMX mode ERROR \n" ); goto clean_and_return; } /* Wait for callback response */ if(sem_wait(&cb_data.sem)) { LOGE("Secure Element opening error"); goto clean_and_return; } if(cb_data.status != NFCSTATUS_SUCCESS) { LOGE("SE set mode failed"); goto clean_and_return; } TRACE("Waiting for notification"); /* Wait for callback response */ if(sem_wait(&cb_data.sem)) { LOGE("Secure Element opening error"); goto clean_and_return; } if(cb_data.status != NFCSTATUS_SUCCESS && cb_data.status != NFCSTATUS_MULTIPLE_PROTOCOLS) { LOGE("SE detection failed"); goto clean_and_return; } CONCURRENCY_UNLOCK(); /* Connect Tag */ CONCURRENCY_LOCK(); TRACE("phLibNfc_RemoteDev_Connect(SMX)"); REENTRANCE_LOCK(); ret = phLibNfc_RemoteDev_Connect(secureElementHandle, com_android_nfc_jni_connect_callback,(void *)&cb_data); REENTRANCE_UNLOCK(); if(ret != NFCSTATUS_PENDING) { LOGE("phLibNfc_RemoteDev_Connect(SMX) returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret)); goto clean_and_return; } TRACE("phLibNfc_RemoteDev_Connect(SMX) returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret)); /* Wait for callback response */ if(sem_wait(&cb_data.sem)) { LOGE("CONNECT semaphore error"); goto clean_and_return; } /* Connect Status */ if(cb_data.status != NFCSTATUS_SUCCESS) { LOGE("Secure Element connect error"); 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(); ret = phLibNfc_Mgt_IoCtl(gHWRef,NFC_MEM_READ,&InParam, &OutParam,com_android_nfc_jni_ioctl_callback, (void *)&cb_data); REENTRANCE_UNLOCK(); if(ret!=NFCSTATUS_PENDING) { LOGE("IOCTL status error"); } /* 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 | 0x40); TRACE("GpioValue to be set = Ox%02x",GpioSetValue[3]); for(i=0;i<4;i++) { TRACE("0x%02x",GpioSetValue[i]); } InParam.buffer = GpioSetValue; InParam.length = 4; OutParam.buffer = Output_Buff; TRACE("phLibNfc_Mgt_IoCtl()- GPIO Set Value"); REENTRANCE_LOCK(); ret = phLibNfc_Mgt_IoCtl(gHWRef,NFC_MEM_WRITE,&InParam, &OutParam,com_android_nfc_jni_ioctl_callback, (void *)&cb_data); REENTRANCE_UNLOCK(); if(ret!=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; } CONCURRENCY_UNLOCK(); /* Return the Handle of the SecureElement */ return secureElementHandle; } else { LOGE("phLibNfc_SE_GetSecureElementList(): No SMX detected"); goto clean_and_return; } } else { LOGE("phLibNfc_SE_GetSecureElementList(): Error"); goto clean_and_return; } clean_and_return: CONCURRENCY_UNLOCK(); return 0; }
// PUBLIC - Used by the programmer to lock the RIO Stack state. This is useful // for example to get the list of available channels without having the list while // looking at each node one-by-one. // Must never be called twice in a row, will lock up. void RemoteIO_Lock() { sem_wait(&RemoteIOLock); }
int main() { sem_t *sem1; //semaphore struct sem_t *sem2; int pid = fork(); if (pid < 0) { perror("fork"); exit(-1); } int i = 0; if (pid > 0) { //parent if ( (sem1 = sem_open(SEM_NAME_1, O_CREAT, 0777, 1)) == SEM_FAILED ) { perror("parent: sem_open"); exit(-1); } if ( (sem2 = sem_open(SEM_NAME_2, O_CREAT, 0777, 1)) == SEM_FAILED ) { perror("parent: sem_open"); exit(-1); } //critical section if (sem_wait(sem1) < 0) //p(s) { perror("parent: sem_wait"); exit(-1); } for (i = 0; i < 500; i++) { printf("Parent #%d\n",i); if (i==250) { printf("PARENT READY\n"); sem_wait(sem2); } } sem_post(sem1); //v(s) //end of critical section } if (0 == pid) { //child if ( (sem1 = sem_open(SEM_NAME_1, O_CREAT, 0777, 1)) == SEM_FAILED ) { perror("parent: sem_open"); exit(-1); } if ( (sem2 = sem_open(SEM_NAME_2, O_CREAT, 0777, 1)) == SEM_FAILED ) { perror("parent: sem_open"); exit(-1); } //critical section if (sem_wait(sem2) < 0) //p(s) { perror("child: sem_wait"); exit(-1); } for (i = 0; i < 500; i++) { printf("Child #%d\n",i); if (i == 250) { printf("CHILD READY\n"); sem_wait(sem1); } } sem_post(sem2); //v(s) //end of critical section } return 0; }