/* * Test pthread_sigmask() with cross fire signaling. * - create 2 threads * - one thread calls pthread_sigmask() and verifies that the specified mask is set * - other thread verifies that the specified mask is not set * - send some signals to each thread, e.g. by pthread_kill and verify that it is blocked or not. * * Note: under heavy load test environment, the signal may not be delivered in timely fashion * * mask thread:----s(READY)-w(SIGMASK)-----------m---s(READY)-w(PTHREADKILL)----------j----s(READY)------w(EXIT)-------s(FINISHED)---------->> * main thread:-w(READY)---------s(SIGMASK)-w(READY)------------c----s(PTHREADKILL)-w(READY)----------k----s(EXIT)--w(FINISHED)--------->> * * main thread:-w(READY)---------s(SIGMASK)-w(READY)------------c----s(PTHREADKILL)----w(FINISHED)---------->> * unmask thread:---s(READY)-w(SIGMASK)-------m--s(READY)-w(PTHREADKILL)----------j----i----s(FINISHED)-------------->> * * where: * m: run pthread_sigmask * c: check result of pthread_sigmask * j: run sigprotected function * k: run pthread_kill * i: signal handler (OMRPORT_SIG_EXCEPTION_RETURN) * */ TEST(PortSignalExtendedTests, sig_ext_test1) { OMRPORT_ACCESS_FROM_OMRPORT(portTestEnv->getPortLibrary()); const char *testName = "omrsig_ext_test1"; omrthread_monitor_t maskMonitor = NULL; omrthread_monitor_t unmaskMonitor = NULL; omrthread_t mainThread = NULL; omrthread_t maskThread = NULL; omrthread_t unmaskThread = NULL; pthread_t osMaskThread = 0; pthread_t osUnmaskThread = 0; uint32_t flags = 0; SigMaskTestInfo maskThreadInfo; SigMaskTestInfo unmaskThreadInfo; intptr_t monitorRC = 0; int memcmp_ret = 0; sigset_t mask; sigset_t oldMask; sigset_t currentMask; sigset_t maskThread_mask; sigset_t unmaskThread_mask; portTestEnv->changeIndent(1); reportTestEntry(OMRPORTLIB, testName); /* initialize local variables */ memset(&maskThreadInfo, 0, sizeof(maskThreadInfo)); memset(&unmaskThreadInfo, 0, sizeof(unmaskThreadInfo)); sigemptyset(&mask); sigemptyset(&oldMask); sigemptyset(¤tMask); sigemptyset(&maskThread_mask); sigemptyset(&unmaskThread_mask); /* * OSX will redirect the SIGILL from the masked thread to other threads unless they are also masked. * This thread's mask will be inherited. Mask SIGILL for all threads for mask testing. */ sigaddset(&mask, SIGILL); if (0 != pthread_sigmask(SIG_SETMASK, &mask, &oldMask)) { outputErrorMessage(PORTTEST_ERROR_ARGS, "pthread_sigmask failed: %s(%d).\n", strerror(errno), errno); FAIL(); } monitorRC = omrthread_monitor_init_with_name(&maskMonitor, 0, "omrsig_ext_sigmask_monitor"); if (0 != monitorRC) { outputErrorMessage(PORTTEST_ERROR_ARGS, "omrthread_monitor_init_with_name failed with %i\n", monitorRC); FAIL(); } setSigMaskTestInfo(&maskThreadInfo, OMRPORTLIB, "Masked Thread", maskMonitor, maskProtectedFunction, INVALID); monitorRC = omrthread_monitor_init_with_name(&unmaskMonitor, 0, "omrsig_ext_sigunmask_monitor"); if (0 != monitorRC) { outputErrorMessage(PORTTEST_ERROR_ARGS, "omrthread_monitor_init_with_name failed with %i\n", monitorRC); FAIL(); } setSigMaskTestInfo(&unmaskThreadInfo, OMRPORTLIB, "Unmasked Thread", unmaskMonitor, unmaskProtectedFunction, INVALID); mainThread = omrthread_self(); maskThread = create_thread(OMRPORTLIB, (omrthread_entrypoint_t)sigMaskThread, &maskThreadInfo); unmaskThread = create_thread(OMRPORTLIB, (omrthread_entrypoint_t)sigMaskThread, &unmaskThreadInfo); if ((NULL != mainThread) && (NULL != maskThread) && (NULL != unmaskThread)) { portTestEnv->log("%s\t:created test threads.\n", testName); /* wait for maskThread and unmaskThread ready */ if (!waitForEvent(testName, &maskThreadInfo, READY, &osMaskThread, sizeof(pthread_t))) { goto exit; } if (!waitForEvent(testName, &unmaskThreadInfo, READY, &osUnmaskThread, sizeof(pthread_t))) { goto exit; } portTestEnv->log("%s\t:test threads are READY.\n", testName); /* test pthread_sigmask */ /* ask maskThread to mask SIGBUS signal */ flags = SIGBUS; portTestEnv->log("%s\t:configure mask thread to mask SIGBUS signal.\n", testName); sendEvent(&maskThreadInfo, SIGMASK, &flags, sizeof(flags)); /* ask unMaskThread to not mask any signal */ flags = 0; portTestEnv->log("%s\t:configure unmask thread to not mask any tested signal.\n", testName); sendEvent(&unmaskThreadInfo, SIGMASK, &flags, sizeof(flags)); portTestEnv->log("%s\t:testing pthread_sigmask...\n", testName); /* check pthread_sigmask result */ if (!waitForEvent(testName, &maskThreadInfo, READY, &maskThread_mask, sizeof(maskThread_mask))) { goto exit; } if (!waitForEvent(testName, &unmaskThreadInfo, READY, &unmaskThread_mask, sizeof(unmaskThread_mask))) { goto exit; } portTestEnv->log("%s\t:operation pthread_sigmask has been done. checking pthread_sigmask result...\n", testName); /* * Expected behavior: * 1. main thread's signal mask shall be untouched * 2. child threads shall inherit main thread's signal mask * 3. child threads' pthread_sigmask operation shall not interfere each other */ if (0 != pthread_sigmask(SIG_SETMASK, NULL, ¤tMask)) { outputErrorMessage(PORTTEST_ERROR_ARGS, "pthread_sigmask failed: %s(%d).\n", strerror(errno), errno); goto exit; } /* check whether main thread signal mask was affected by child thread pthread_sigmask operation */ if (0 != (memcmp_ret = memcmp(¤tMask, &mask, sizeof(currentMask)))) { outputErrorMessage(PORTTEST_ERROR_ARGS, "main thread mask was modified (old=0x%X, new=0x%X), %X\n", *((uint32_t *)&mask), *((uint32_t *)¤tMask), memcmp_ret); goto exit; } else { portTestEnv->log("%s\t:main thread signal mask was not affected.\n", testName); } /* UNIX opengroup example says that newly created thread shall inherit the mask */ if (!sigismember(&maskThread_mask, SIGILL) || !sigismember(&unmaskThread_mask, SIGILL)) { outputErrorMessage(PORTTEST_ERROR_ARGS, "created threads did not inherit mask.(maskThreadInfo=0x%X, unmaskThreadInfo=0x%X)\n", *((uint32_t *)&maskThread_mask), *((uint32_t *)&unmaskThread_mask)); goto exit; } else { portTestEnv->log("%s\t:child thread inherited main thread's signal mask.\n", testName); } /* Check whether two child threads' pthread_sigmask operation can interfere each other. */ if (!sigismember(&maskThread_mask, SIGBUS) || sigismember(&unmaskThread_mask, SIGBUS)) { outputErrorMessage(PORTTEST_ERROR_ARGS, "pthread_sigmask did not work.(maskThreadInfo=0x%X, unmaskThreadInfo=0x%X)\n", *((uint32_t *)&maskThread_mask), *((uint32_t *)&unmaskThread_mask)); goto exit; } else { portTestEnv->log("%s\t:pthread_sigmask operation in each child thread did not interfere each other.\n", testName); } /* * test unmask thread signal handling behavior * unmask thread will install SIGSEGV handler and launch a protected function unmaskProtectedFunction(). * unmaskProtectedFunction() shall be terminated by SIGSEGV generated in its body, and the unmask thread * will send report to this main thread. */ flags = OMRPORT_SIG_FLAG_MAY_RETURN | OMRPORT_SIG_FLAG_SIGSEGV; /* SIGSEGV shall be received */ portTestEnv->log("%s\t:configure unmask thread to prepare for unmasked signal SIGSEGV test.\n", testName); sendEvent(&unmaskThreadInfo, PTHREADKILL, &flags, sizeof(flags)); if (!waitForEvent(testName, &unmaskThreadInfo, FINISHED, NULL, 0)) { goto exit; } else { portTestEnv->log("%s\t:unmasked thread finished. checking unmask thread's signal status...\n", testName); if (unmaskThreadInfo.bulletinBoard.status == SIGNALED) { portTestEnv->log("%s\t:unmasked thread received signal as expected.\n", testName); } else { outputErrorMessage(PORTTEST_ERROR_ARGS, "unmasked thread did not received signal as expected.(SignalStatus=%d)\n", unmaskThreadInfo.bulletinBoard.status); goto exit; } } /* * test mask thread signal handling behavior * mask thread will install SIGILL handler and launch a protected function maskProtectedFunction(). */ portTestEnv->log("%s\t:testing pthread_kill...\n", testName); flags = OMRPORT_SIG_FLAG_MAY_RETURN | OMRPORT_SIG_FLAG_SIGILL; /* SIGILL shall not be received */ sendEvent(&maskThreadInfo, PTHREADKILL, &flags, sizeof(flags)); portTestEnv->log("%s\t:configure mask thread to prepare for pthread_kill test.\n", testName); if (!waitForEvent(testName, &maskThreadInfo, READY, NULL, 0)) { goto exit; } portTestEnv->log("%s\t:mask thread is ready to receive signal. sending pthread_kill...\n", testName); /* send SIGILL to maskThread which will never receive this signal */ pthread_kill(osMaskThread, SIGILL); /* check pthread_kill result */ /* * Expected behavior: * 1. child thread with signal mask on SIGILL shall not receive this signal and therefore NOTSIGNALED. */ portTestEnv->log("%s\t:notify mask thread to exit.\n", testName); sendEvent(&maskThreadInfo, EXIT, NULL, 0); if (!waitForEvent(testName, &maskThreadInfo, FINISHED, NULL, 0)) { goto exit; } else { portTestEnv->log("%s\t:masked thread finished. checking mask thread's signal status...\n", testName); if (maskThreadInfo.bulletinBoard.status == NOTSIGNALED) { portTestEnv->log("%s\t:masked thread did not receive signal as expected.\n", testName); } else { outputErrorMessage(PORTTEST_ERROR_ARGS, "masked thread received signal as not expected.(SignalStatus=%d)\n", maskThreadInfo.bulletinBoard.status); goto exit; } } portTestEnv->log("%s\t:pthread_sigmask works on each individual thread.\n", testName); } portTestEnv->log("%s\t:destroying unmaskMonitor...\n", testName); omrthread_monitor_destroy(unmaskMonitor); portTestEnv->log("%s\t:destroying maskMonitor...\n", testName); omrthread_monitor_destroy(maskMonitor); goto cleanup; exit: portTestEnv->log(LEVEL_ERROR, "%s\t:test stopped with errors\n", testName); FAIL(); cleanup: /* restore signal mask */ pthread_sigmask(SIG_SETMASK, &oldMask, NULL); portTestEnv->changeIndent(-1); reportTestExit(OMRPORTLIB, testName); }
int main(const int argc, const char *argv[]) { char buf[BUFFER_MAX]; struct sockaddr addr; socklen_t alen; int lsocket, s, count; pthread_t worker_threads, signal_thread; pthread_attr_t pthread_custom_attr; sigset_t sigs_to_block; pthread_mutex_init(&io_mutex, NULL); pthread_cond_init(&io_wait, NULL); pthread_attr_init(&pthread_custom_attr); sigemptyset(&sigs_to_block); sigaddset(&sigs_to_block, SIGIO); pthread_sigmask(SIG_BLOCK, &sigs_to_block, NULL); pthread_create(&signal_thread, &pthread_custom_attr, io_signal_handler, NULL); ALOGI("installd firing up\n"); if (initialize_globals() < 0) { ALOGE("Could not initialize globals; exiting.\n"); exit(1); } if (initialize_directories() < 0) { ALOGE("Could not create directories; exiting.\n"); exit(1); } drop_privileges(); lsocket = android_get_control_socket(SOCKET_PATH); if (lsocket < 0) { ALOGE("Failed to get socket from environment: %s\n", strerror(errno)); exit(1); } if (listen(lsocket, 5)) { ALOGE("Listen on socket failed: %s\n", strerror(errno)); exit(1); } fcntl(lsocket, F_SETFD, FD_CLOEXEC); for (;;) { alen = sizeof(addr); s = accept(lsocket, &addr, &alen); if (s < 0) { ALOGE("Accept failed: %s\n", strerror(errno)); continue; } fcntl(s, F_SETFD, FD_CLOEXEC); fcntl(s, F_SETFL, O_ASYNC | O_NONBLOCK); fcntl(s, F_SETSIG, 0); fcntl(s, F_SETOWN, getpid()); write_error = 0; ALOGI("new connection\n"); for (;;) { unsigned short count; int id; if (readx(s, &id, sizeof(id))) { ALOGE("failed to read transaction id\n"); break; } if (readx(s, &count, sizeof(count))) { ALOGE("failed to read size\n"); break; } if ((count < 1) || (count >= BUFFER_MAX)) { ALOGE("invalid size %d\n", count); break; } if (readx(s, buf, count)) { ALOGE("failed to read command\n"); break; } buf[count] = 0; thread_parm *args = (thread_parm*) malloc(sizeof(thread_parm)); args->s = s; strncpy(args->cmd, buf, count + 1); args->id = id; pthread_create(&worker_threads, &pthread_custom_attr, executeAsync, (void*) args); } ALOGI("closing connection\n"); close(s); } pthread_kill(&signal_thread, SIGKILL); pthread_join(&signal_thread, NULL); return 0; }
/* Wake up the RPC manager and all spawned threads so they can exit */ extern void rpc_mgr_wake(void) { if (master_thread_id) pthread_kill(master_thread_id, SIGUSR1); slurm_persist_conn_recv_server_fini(); }
void abort_site_update(GtkWidget * button, gpointer data) { extern pthread_t update_tid; gtk_label_set(GTK_LABEL(status_label), "Aborting..."); pthread_kill(update_tid, SIGUSR1); }
int main(int argc, char *argv[]) { int res; int i; int j; int cnt; pthread_t vth[NTH]; sigset_t set; struct sigaction accion; /* Programacion de los manejadores */ sigemptyset(&set); for(i=SIGRTMIN; i<=SIGRTMAX; i++) { sigaddset(&set, i); /* Conjunto con todas las S.T.R. */ accion.sa_sigaction = manej; /* Todas tienen el mismo manejador */ sigemptyset(&(accion.sa_mask)); accion.sa_flags = SA_SIGINFO; sigaction(i, &accion, NULL); } /* Preparacion de la mascara del hilo "main": No ve ninguna senal de tiempo real */ pthread_sigmask(SIG_BLOCK, &set, NULL); /* Primera prueba: kill */ /* Arrancan NTH threads */ printf("\nPrimera prueba: senales generadas con kill\n\n"); for(i = 0; i < NTH; i++) pthread_create(vth + i, NULL, hilo /*hilo2*/, (void *)i); for(i=0; i < NTH; i++) { /* El proceso se autosenala */ printf("main enviando senal %d\n", i+SIGRTMIN); kill(getpid(), i+SIGRTMIN); nanosleep(&tim, NULL); /* Espera un tiempo */ } /* Ahora cancela los hilos */ for(i=0; i < NTH; i++) { printf("main cancelando al hilo %d\n", i); pthread_cancel(vth[i]); pthread_join(vth[i], NULL); } nanosleep(&tim, NULL); /* Segunda prueba: Senales generadas con pthread_kill */ printf("\nSegunda prueba: senales generadas con pthread_kill\n\n"); for(i=0; i < NTH; i++) pthread_create(vth + i, NULL, hilo, (void *)i); nanosleep(&tim, NULL); for(i=0; i<NTH; i++) { /* Senales a los diferentes threads */ printf("Main enviando senal %d a los %d threads\n", i + SIGRTMIN, NTH); for(j=0; j<NTH; j++) { if((res = pthread_kill(vth[j], i+SIGRTMIN)) != 0) printf("Main; error %d en pthread_kill\n", res); } nanosleep(&tim, NULL); /* Espera un tiempo */ } /* Ahora cancela los hilos */ for(i=0; i < NTH; i++) { printf("cancelando el hilo %d\n", i); pthread_cancel(vth[i]); pthread_join(vth[i], NULL); } nanosleep(&tim, NULL); /* Tercera prueba: Senales capturadas con manejador */ printf("\nTercera prueba: Senales capturadas con manejador\n\n"); for(i=0; i < NTH; i++) pthread_create(vth + i, NULL, hilo2, (void *)i); nanosleep(&tim, NULL); i = 0; cnt = 1; for(i=0; i<NTH; i++) { /* Senales dirigidas a los diferentes threads */ printf("Main enviando senal %d\n", i + SIGRTMIN); for(j=0; j<NTH; j++) { if((res = pthread_kill(vth[j], i+SIGRTMIN)) != 0) printf("Main; error %d en pthread_kill\n", res); nanosleep(&tim, NULL); /* Espera un tiempo */ } } printf("\nCuarta prueba: Error de segmentacion\n\n"); pthread_create(&otroth, NULL, erroneo, (void *)0); /* Fin del programa */ for(i=0; i<20; i++) nanosleep(&tim, NULL); printf("Soy main; voy a acabar\n"); return 0; }
void * threadPiece(void *p) { int rot, i, j, col_min, ligne_min, pieceValidee; CASE casesVerif[NB_CASES]; pthread_mutex_lock(&mutexPieceEnCours); // petit lock pour pouvoir unlock juste en dessous :D while (1) { pieceEnCours = pieces[rand() % 7]; // pieceEnCours = pieces[0]; rot = rand() % 4; for (i = 0 ; i < rot ; ++i) RotationPiece(&pieceEnCours); TranslationCases(pieceEnCours.cases, pieceEnCours.nbCases); // Tri sur ligne/colonne qsort(pieceEnCours.cases, pieceEnCours.nbCases , sizeof(CASE), compare_case); // On autorise le thread fin à vérifier si on peut insérer la nouvelle pièce pthread_mutex_unlock(&mutexPieceEnCours); // Effacement de la zone "pièce en cours" for (i = 0 ; i < 4 ; ++i) { for (j = 0 ; j < 4 ; ++j) { EffaceCarre(3 + i , 15 + j ); } } // Affichage de la pièce en cours: for (i = 0 ; i < pieceEnCours.nbCases ; ++i) { DessineSprite(3 + pieceEnCours.cases[i].ligne, 15 + pieceEnCours.cases[i].colonne, pieceEnCours.professeur); } pieceValidee = 0; while (!pieceValidee) { // On attend que toutes les pièces soient insérées par le joueur pthread_mutex_lock(&mutexCasesInserees); while (nbCasesInserees < pieceEnCours.nbCases) { pthread_cond_wait(&condCasesInserees, &mutexCasesInserees); } pthread_mutex_unlock(&mutexCasesInserees); // Tri des cases insérées qsort(casesInserees, nbCasesInserees, sizeof(CASE), compare_case); // Vérification de la position des cases insérées par rapport à la pièce en cours memcpy(casesVerif, casesInserees, sizeof(CASE) * NB_CASES); TranslationCases(casesVerif, nbCasesInserees); pieceValidee = 1; for (i = 0 ; i < nbCasesInserees && pieceValidee == 1 ; ++i) { if (compare_case(&(pieceEnCours.cases[i]), &(casesVerif[i])) != 0) pieceValidee = 0; } if (pieceValidee) { for (i = 0 ; i < nbCasesInserees ; ++i) { tab[casesInserees[i].ligne][casesInserees[i].colonne] = BRIQUE; DessineSprite(casesInserees[i].ligne, casesInserees[i].colonne, BRIQUE); } // On réveille le threadScore et on incrémente le score pthread_mutex_lock(&mutexScore); ++score; MAJScore = 1; pthread_mutex_unlock(&mutexScore); pthread_cond_signal(&condScore); // On empêche le thread Fin de lire la pièce avant que la nouvelle ne soit générée pthread_mutex_lock(&mutexPieceEnCours); // On réveille les 4 threads case for (i = 0 ; i < nbCasesInserees ; ++i) { pthread_kill(threadHandleCase[casesInserees[i].ligne][casesInserees[i].colonne], SIGUSR1); } } else { for (i = 0 ; i < nbCasesInserees ; ++i) { EffaceCarre(casesInserees[i].ligne, casesInserees[i].colonne); tab[casesInserees[i].ligne][casesInserees[i].colonne] = VIDE; } pthread_mutex_lock(&mutexTraitement); traitementEnCours = 0; pthread_mutex_unlock(&mutexTraitement); DessineSprite(12, 11, VOYANT_VERT); } pthread_mutex_lock(&mutexCasesInserees); nbCasesInserees = 0; pthread_mutex_unlock(&mutexCasesInserees); } } }
static void _service_run (srvmode_t mode, int rfdno, int wfdno) { List l = diod_conf_get_listen (); int nwthreads = diod_conf_get_nwthreads (); int flags = diod_conf_get_debuglevel (); uid_t euid = geteuid (); int n; ss.mode = mode; ss.rfdno = rfdno; ss.wfdno = wfdno; ss.shutdown = 0; ss.reload = 0; _service_sigsetup (); ss.fds = NULL; ss.nfds = 0; switch (mode) { case SRV_FILEDES: break; case SRV_NORMAL: if (!diod_sock_listen_hostports (l, &ss.fds, &ss.nfds, NULL)) msg_exit ("failed to set up listen ports"); #if WITH_RDMATRANS ss.rdma = diod_rdma_create (); diod_rdma_listen (ss.rdma); #endif #if WITH_ETHERTRANS ss.ether = diod_ether_create(); diod_ether_listen(ss.ether); #endif break; } /* manipulate squash/runas users if not root */ if (euid != 0) { if (diod_conf_get_allsquash ()) { struct passwd *pw = getpwuid (euid); char *su = diod_conf_get_squashuser (); if (!pw) msg_exit ("getpwuid on effective uid failed"); if (strcmp (pw->pw_name, su) != 0) { if (strcmp (su, DFLT_SQUASHUSER) != 0) msg ("changing squashuser '%s' to '%s' " "since you are not root", su, pw->pw_name); diod_conf_set_squashuser (pw->pw_name); /* fixes issue 41 */ } } else { /* N.B. runasuser cannot be set in the config file */ uid_t ruid = diod_conf_get_runasuid (); if (diod_conf_opt_runasuid () && ruid != euid) msg ("changing runasuid %d to %d " "since you are not root", ruid, euid); diod_conf_set_runasuid (euid); } } if (!diod_conf_get_foreground () && mode == SRV_NORMAL) _daemonize (); /* implicit fork - no pthreads before this */ if (!diod_conf_get_foreground () && mode != SRV_FILEDES) diod_log_set_dest (diod_conf_get_logdest ()); /* drop root */ if (euid == 0) { if (diod_conf_get_allsquash ()) _become_user (diod_conf_get_squashuser (), -1, 1); else if (diod_conf_opt_runasuid ()) _become_user (NULL, diod_conf_get_runasuid (), 1); } /* clear umask */ umask (0); flags |= SRV_FLAGS_LOOSEFID; /* work around buggy clients */ flags |= SRV_FLAGS_AUTHCONN; //flags |= SRV_FLAGS_FLUSHSIG; /* XXX temporarily off */ if (geteuid () == 0) { flags |= SRV_FLAGS_SETFSID; flags |= SRV_FLAGS_DAC_BYPASS; if (_test_setgroups ()) flags |= SRV_FLAGS_SETGROUPS; else msg ("test_setgroups: groups are per-process (disabling)"); } /* Process dumpable flag may have been cleared by uid manipulation above. * Set it here, then maintain it in user.c::np_setfsid () as uids are * further manipulated. */ if (prctl (PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) err_exit ("prctl PR_SET_DUMPABLE failed"); if (!diod_conf_get_userdb ()) flags |= SRV_FLAGS_NOUSERDB; if (!(ss.srv = np_srv_create (nwthreads, flags))) /* starts threads */ errn_exit (np_rerror (), "np_srv_create"); if (diod_init (ss.srv) < 0) errn_exit (np_rerror (), "diod_init"); if ((n = pthread_create (&ss.t, NULL, _service_loop, NULL))) errn_exit (n, "pthread_create _service_loop"); #if WITH_RDMATRANS if ((n = pthread_create (&ss.rdma_t, NULL, _service_loop_rdma, NULL))) errn_exit (n, "pthread_create _service_loop_rdma"); #endif #if WITH_ETHERTRANS if ((n = pthread_create (&ss.ether_t, NULL, _service_loop_ether, NULL))) errn_exit (n, "pthread_create _service_loop_ether"); #endif switch (mode) { case SRV_FILEDES: np_srv_wait_conncount (ss.srv, 1); pthread_kill (ss.t, SIGUSR1); break; case SRV_NORMAL: break; } if ((n = pthread_join (ss.t, NULL))) errn_exit (n, "pthread_join _service_loop"); #if WITH_RDMATRANS if ((n = pthread_join (ss.rdma_t, NULL))) errn_exit (n, "pthread_join _service_loop_rdma"); #endif #if WITH_ETHERTRANS if ((n = pthread_join (ss.ether_t, NULL))) errn_exit (n, "pthread_join _service_loop_ether"); #endif diod_fini (ss.srv); np_srv_destroy (ss.srv); }
int push_object_to_thread (void *object, pmda threadr, dt_score_ptp scalc, pthread_t *st) { mutex_lock (&threadr->mutex); p_md_obj thrd_ptr = threadr->first; po_thrd sel_thread = NULL; float lowest_score = 10000000.0; while (thrd_ptr) { po_thrd thread = (po_thrd) thrd_ptr->ptr; mutex_lock (&thread->in_objects.mutex); mutex_lock (&thread->proc_objects.mutex); if (thread->in_objects.offset == thread->in_objects.count) { goto end_l; } float score = scalc (&thread->in_objects, &thread->proc_objects, object, (void*) thread); if (0.0 == score) { pthread_mutex_unlock (&thread->in_objects.mutex); pthread_mutex_unlock (&thread->proc_objects.mutex); sel_thread = thread; break; } if (score == -1.0) { goto end_l; } if (score < lowest_score) { sel_thread = thread; lowest_score = score; } end_l: ; pthread_mutex_unlock (&thread->in_objects.mutex); pthread_mutex_unlock (&thread->proc_objects.mutex); thrd_ptr = thrd_ptr->next; } int r; if (NULL == sel_thread) { pthread_mutex_unlock (&threadr->mutex); return 1; } mutex_lock (&sel_thread->in_objects.mutex); if (NULL == md_alloc_le (&sel_thread->in_objects, 0, 0, (void*) object)) { r = 2; } else { r = 0; //if (sel_thread->status & F_THRD_STATUS_SUSPENDED) // { *st = sel_thread->pt; pthread_kill (sel_thread->pt, SIGUSR1); // } } pthread_mutex_unlock (&sel_thread->in_objects.mutex); pthread_mutex_unlock (&threadr->mutex); return r; }
void ast_tcptls_server_start(struct ast_tcptls_session_args *desc) { int flags; int x = 1; int tls_changed = 0; if (desc->tls_cfg) { char hash[41]; char *str = NULL; struct stat st; /* Store the hashes of the TLS certificate etc. */ if (stat(desc->tls_cfg->certfile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->certfile))) { memset(hash, 0, 41); } else { ast_sha1_hash(hash, str); } ast_free(str); str = NULL; memcpy(desc->tls_cfg->certhash, hash, 41); if (stat(desc->tls_cfg->pvtfile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->pvtfile))) { memset(hash, 0, 41); } else { ast_sha1_hash(hash, str); } ast_free(str); str = NULL; memcpy(desc->tls_cfg->pvthash, hash, 41); if (stat(desc->tls_cfg->cafile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->cafile))) { memset(hash, 0, 41); } else { ast_sha1_hash(hash, str); } ast_free(str); str = NULL; memcpy(desc->tls_cfg->cahash, hash, 41); /* Check whether TLS configuration has changed */ if (!desc->old_tls_cfg) { /* No previous configuration */ tls_changed = 1; desc->old_tls_cfg = ast_calloc(1, sizeof(*desc->old_tls_cfg)); } else if (memcmp(desc->tls_cfg->certhash, desc->old_tls_cfg->certhash, 41)) { tls_changed = 1; } else if (memcmp(desc->tls_cfg->pvthash, desc->old_tls_cfg->pvthash, 41)) { tls_changed = 1; } else if (strcmp(desc->tls_cfg->cipher, desc->old_tls_cfg->cipher)) { tls_changed = 1; } else if (memcmp(desc->tls_cfg->cahash, desc->old_tls_cfg->cahash, 41)) { tls_changed = 1; } else if (strcmp(desc->tls_cfg->capath, desc->old_tls_cfg->capath)) { tls_changed = 1; } else if (memcmp(&desc->tls_cfg->flags, &desc->old_tls_cfg->flags, sizeof(desc->tls_cfg->flags))) { tls_changed = 1; } if (tls_changed) { ast_debug(1, "Changed parameters for %s found\n", desc->name); } } /* Do nothing if nothing has changed */ if (!tls_changed && !ast_sockaddr_cmp(&desc->old_address, &desc->local_address)) { ast_debug(1, "Nothing changed in %s\n", desc->name); return; } /* If we return early, there is no one listening */ ast_sockaddr_setnull(&desc->old_address); /* Shutdown a running server if there is one */ if (desc->master != AST_PTHREADT_NULL) { pthread_cancel(desc->master); pthread_kill(desc->master, SIGURG); pthread_join(desc->master, NULL); } if (desc->accept_fd != -1) { close(desc->accept_fd); } /* If there's no new server, stop here */ if (ast_sockaddr_isnull(&desc->local_address)) { ast_debug(2, "Server disabled: %s\n", desc->name); return; } desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->local_address) ? AF_INET6 : AF_INET, SOCK_STREAM, 0); if (desc->accept_fd < 0) { ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno)); return; } setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x)); if (ast_bind(desc->accept_fd, &desc->local_address)) { ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n", desc->name, ast_sockaddr_stringify(&desc->local_address), strerror(errno)); goto error; } if (listen(desc->accept_fd, 10)) { ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name); goto error; } flags = fcntl(desc->accept_fd, F_GETFL); fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK); if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) { ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n", desc->name, ast_sockaddr_stringify(&desc->local_address), strerror(errno)); goto error; } /* Set current info */ ast_sockaddr_copy(&desc->old_address, &desc->local_address); if (desc->old_tls_cfg) { ast_free(desc->old_tls_cfg->certfile); ast_free(desc->old_tls_cfg->pvtfile); ast_free(desc->old_tls_cfg->cipher); ast_free(desc->old_tls_cfg->cafile); ast_free(desc->old_tls_cfg->capath); desc->old_tls_cfg->certfile = ast_strdup(desc->tls_cfg->certfile); desc->old_tls_cfg->pvtfile = ast_strdup(desc->tls_cfg->pvtfile); desc->old_tls_cfg->cipher = ast_strdup(desc->tls_cfg->cipher); desc->old_tls_cfg->cafile = ast_strdup(desc->tls_cfg->cafile); desc->old_tls_cfg->capath = ast_strdup(desc->tls_cfg->capath); memcpy(desc->old_tls_cfg->certhash, desc->tls_cfg->certhash, 41); memcpy(desc->old_tls_cfg->pvthash, desc->tls_cfg->pvthash, 41); memcpy(desc->old_tls_cfg->cahash, desc->tls_cfg->cahash, 41); memcpy(&desc->old_tls_cfg->flags, &desc->tls_cfg->flags, sizeof(desc->old_tls_cfg->flags)); } return; error: close(desc->accept_fd); desc->accept_fd = -1; }
//-------------------------------------------------- int main(int argc, char* argv[]) { fileName = calloc(20, sizeof(char)); word = calloc(10, sizeof(char)); if(argc != 3) { printf("\nBledna ilosc argumentow!\n" "Poprawny sposob wywolania programu to:\n" "[nazwa programu] [numer testu] [numer signru]\n\n" "Available signals:\t10 - SIGUSR1\t15 - SIGTERM\t 9 - SIGKILL\t19 - SIGSTOP\n" "Tests: 1 - 5 wg. tresci zadania\n\n"); exit(-1); } numOfThreads = 5; strcpy(fileName, "somefile"); numOfRecords = 2; strcpy(word, "slowo"); test = atoi(argv[1]); signr = atoi(argv[2]); if((file = open(fileName, O_RDONLY)) == -1) { printf("open(): %d: %s\n", errno, strerror(errno)); exit(-1); } threads = calloc(numOfThreads, sizeof(pthread_t)); int i; for(i = 0; i < numOfThreads; i++){ if(pthread_create(&threads[i], NULL, threadFunction, NULL) != 0) { printf("pthread_create(): %d: %s\n", errno, strerror(errno)); exit(-1); } } if(test == 1){ kill(getpid(), signr); } else if(test == 2) { signal(signr, SIG_IGN); kill(getpid(), signr); } else if(test == 4) { if(pthread_kill(threads[0], signr) != 0){ printf("pthread_kill(): %d: %s\n", errno, strerror(errno)); exit(1); } } else if(test == 3) { if(signal(SIGUSR1, signalHandler) == SIG_ERR){ printf("signal(): %d: %s\n", errno, strerror(errno)); exit(-1); } if(signal(SIGTERM, signalHandler) == SIG_ERR){ printf("signal(): %d: %s\n", errno, strerror(errno)); exit(-1); } kill(getpid(), signr); } else if(test == 5) { if(pthread_kill(threads[0], signr) != 0){ printf("pthread_kill(): %d: %s\n", errno, strerror(errno)); exit(1); } } STARTJOB = 0; for(i = 0; i < numOfThreads; i++) { pthread_join(threads[i], NULL); } free(threads); close(file); return 0; }
void stop_dispatcher() { pthread_kill(dispatcher_t, SIGUSR1); }
void test_ssl() { interface ifs[16]; active_interfaces(ifs, 16); char *passwd = "password"; char *dir = chdir_temp_dir(); kdfp kdfp = { .N = 2, .r = 1, .p = 1}; uint8_t kek[KEY_LEN] = { 0 }; struct server_cfg cfg = { .passwd = passwd, .cert = "server.pem", .ifa = &ifs[0], }; pthread_t tid; EC_GROUP *group = EC_GROUP_new_by_curve_name(OBJ_txt2nid(EC_CURVE_NAME)); EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE); init_certs(group, passwd, "server.pem", "client.pem"); init_certs(group, passwd, "zerver.pem", "zlient.pem"); init_index("index", kek, &kdfp); EC_GROUP_free(group); assert(pthread_create(&tid, NULL, &run_server, &cfg) == 0); struct timeval timeout = { .tv_usec = 500 }; uint32_t usecs = 10000; sockaddr6 addr; X509 *cert = NULL, *sert = NULL; EVP_PKEY *pk = NULL, *sk = NULL; SSL_CTX *ctx = NULL; SSL *ssl = NULL; uint8_t data[KDFP_LEN]; // client/server cert & pk mismatch read_pem("client.pem", NULL, passwd, &pk, 2, &sert, &cert); read_pem("server.pem", NULL, passwd, &sk, 0); assert(client_ctx(sert, cert, sk) == NULL); assert(server_sock(&ctx, sert, pk, cfg.ifa, &addr) == -1); assert(ctx == NULL); cleanup(&ctx, &ssl, &sert, &cert, &sk, &pk); // incorrect signature on pong read_pem("zerver.pem", NULL, passwd, &sk, 1, &sert); assert(find_server(sk, &addr, usecs, 30) == false); cleanup(&ctx, &ssl, &sert, &cert, &sk, &pk); // incorrect server certificate read_pem("server.pem", NULL, passwd, &sk, 1, &sert); assert(find_server(sk, &addr, usecs, 30) == true); cleanup(&ctx, &ssl, &sert, &cert, &sk, &pk); read_pem("client.pem", NULL, passwd, &pk, 2, &sert, &cert); X509_free(sert); read_pem("zerver.pem", NULL, passwd, &sk, 1, &sert); ctx = client_ctx(sert, cert, pk); assert(client_socket(ctx, &addr, &timeout) == NULL); assert(ERR_GET_REASON(ERR_get_error()) == SSL_R_CERTIFICATE_VERIFY_FAILED); cleanup(&ctx, &ssl, &sert, &cert, &sk, &pk); // incorrect client certificate read_pem("zlient.pem", NULL, passwd, &pk, 1, &cert); read_pem("server.pem", NULL, passwd, &sk, 1, &sert); ctx = client_ctx(sert, cert, pk); assert(client_socket(ctx, &addr, &timeout) == NULL); cleanup(&ctx, &ssl, &sert, &cert, &sk, &pk); // valid certificates read_pem("client.pem", NULL, passwd, &pk, 2, &sert, &cert); read_pem("server.pem", NULL, passwd, &sk, 0); ctx = client_ctx(sert, cert, pk); assert((ssl = client_socket(ctx, &addr, &timeout))); assert(SSL_read(ssl, &data, KDFP_LEN) == KDFP_LEN); cleanup(&ctx, &ssl, &sert, &cert, &sk, &pk); pthread_kill(tid, SIGINT); pthread_join(tid, NULL); unlink("server.pem"); unlink("client.pem"); unlink("zerver.pem"); unlink("zlient.pem"); unlink("index"); rmdir_temp_dir(dir); }
TEST(pthread, pthread_kill__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); ASSERT_EQ(ESRCH, pthread_kill(dead_thread, 0)); }
TEST(pthread, pthread_kill__in_signal_handler) { ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper); ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM)); }
int do_test (void) { pthread_t th; struct sigaction sa; sigemptyset (&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = handler; if (sigaction (SIGUSR1, &sa, NULL) != 0) { puts ("sigaction failed"); exit (1); } if (pthread_barrier_init (&b, NULL, 2) != 0) { puts ("barrier_init failed"); exit (1); } if (pthread_create (&th, NULL, tf, NULL) != 0) { puts ("create failed"); exit (1); } int e = pthread_barrier_wait (&b); if (e != 0 && e != PTHREAD_BARRIER_SERIAL_THREAD) { puts ("barrier_wait failed"); exit (1); } if (pthread_mutex_lock (&m) != 0) { puts ("mutex_lock failed"); exit (1); } /* Send the thread a signal which it has blocked. */ if (pthread_kill (th, SIGUSR1) != 0) { puts ("kill failed"); exit (1); } if (pthread_mutex_unlock (&m) != 0) { puts ("mutex_unlock failed"); exit (1); } void *r; if (pthread_join (th, &r) != 0) { puts ("join failed"); exit (1); } if (r != NULL) { puts ("return value wrong"); exit (1); } return 0; }
int raise(int sig) { return pthread_kill(pthread_self(), sig); }
bool vrpn_Thread::kill() { // kill the os thread #if defined(sgi) || defined(_WIN32) if (threadID>0) { #ifdef sgi if (::kill( (long) threadID, SIGKILL)<0) { perror("vrpn_Thread::kill: kill:"); return false; } #elif defined(_WIN32) // Return value of -1 passed to TerminateThread causes a warning. if (!TerminateThread( (HANDLE) threadID, 1 )) { fprintf(stderr, "vrpn_Thread::kill: problem with terminateThread call.\n"); return false; } #endif #else if (threadID) { // Posix by default if (pthread_kill(threadID, SIGKILL) != 0) { perror("vrpn_Thread::kill:pthread_kill: "); return false; } #endif } else { fprintf(stderr, "vrpn_Thread::kill: thread is not currently alive.\n"); return false; } threadID = 0; return true; } bool vrpn_Thread::running() { return threadID!=0; } #if defined(sgi) || defined(_WIN32) unsigned long vrpn_Thread::pid() { #else pthread_t vrpn_Thread::pid() { #endif return threadID; } bool vrpn_Thread::available() { #ifdef vrpn_THREADS_AVAILABLE return true; #else return false; #endif } void vrpn_Thread::userData( void *pvNewUserData ) { td.pvUD = pvNewUserData; } void *vrpn_Thread::userData() { return td.pvUD; } void vrpn_Thread::threadFuncShell( void *pvThread ) { vrpn_Thread *pth = (vrpn_Thread *)pvThread; pth->pfThread( pth->td ); // thread has stopped running pth->threadID = 0; } // This is a Posix-compatible function prototype that // just calls the other function. void *vrpn_Thread::threadFuncShellPosix( void *pvThread ) { threadFuncShell(pvThread); return NULL; }
/** * Execution entry point of the terminal server application. Launches each controller as a thread * with its needed sockets for inter process communication. * * Revisions: * -# none. * * @param[in] argc Number of command line arguments. * @param[in] argv Array of command line arguments. * @return void * * @designer Andrew Burian * @author Andrew Burian * * @date February 1, 2014 */ int main(int argc, char* argv[]) { SOCKET uiSockSet[2]; SOCKET connectionSockSet[2]; SOCKET generalSockSet[2]; SOCKET gameplaySockSet[2]; SOCKET keepAliveSockSet[2]; SOCKET timerSockSet[2]; SOCKET out_in[2]; SOCKET out_gen[2]; SOCKET out_game[2]; SOCKET out_keepal[2]; SOCKET uiParams[1]; SOCKET conManParams[1]; SOCKET generalParams[2]; SOCKET gameplayParams[2]; SOCKET outboundParams[4]; SOCKET inboundParams[6]; SOCKET keepAliveParams[2]; SOCKET timerParams[1]; pthread_t controllers[NUM_CONTROLLERS]; int threadResult = 0; int i = 0; printf("%s\n%s\n%s%.1lf\n%s\n\n", "-------------------------------------------------------------", " Cut The Power ", " Server v", SERVER_VERSION, "-------------------------------------------------------------"); DEBUG(DEBUG_ALRM, "Started With Debug"); DEBUG(DEBUG_ALRM, " - Alarms [on]"); DEBUG(DEBUG_WARN, " - Warnings [on]"); DEBUG(DEBUG_INFO, " - Information [on]"); //signal(SIGINT, KillHandler); setupPacketInfo(); if (socketpair(AF_UNIX, SOCK_STREAM, 0, uiSockSet) == -1) { fprintf(stderr, "Socket pair error: uiSockSet"); return -1; } if (socketpair(AF_UNIX, SOCK_STREAM, 0, out_in) == -1) { fprintf(stderr, "Socket pair error: outswitchSockSet"); return -1; } if (socketpair(AF_UNIX, SOCK_STREAM, 0, out_game) == -1) { fprintf(stderr, "Socket pair error: outswitchSockSet"); return -1; } if (socketpair(AF_UNIX, SOCK_STREAM, 0, out_gen) == -1) { fprintf(stderr, "Socket pair error: outswitchSockSet"); return -1; } if (socketpair(AF_UNIX, SOCK_STREAM, 0, out_keepal) == -1) { fprintf(stderr, "Socket pair error: outswitchSockSet"); return -1; } if (socketpair(AF_UNIX, SOCK_STREAM, 0, connectionSockSet) == -1) { fprintf(stderr, "Socket pair error: connectionSockSet"); return -1; } if (socketpair(AF_UNIX, SOCK_STREAM, 0, generalSockSet) == -1) { fprintf(stderr, "Socket pair error: generalSockSet"); return -1; } if (socketpair(AF_UNIX, SOCK_STREAM, 0, gameplaySockSet) == -1) { fprintf(stderr, "Socket pair error: gameplaySockSet"); return -1; } if (socketpair(AF_UNIX, SOCK_STREAM, 0, keepAliveSockSet) == -1) { fprintf(stderr, "Socket pair error: keepAliveSockSet"); return -1; } if (socketpair(AF_UNIX, SOCK_STREAM, 0, timerSockSet) == -1) { fprintf(stderr, "Socket pair error: timerSockSet"); return -1; } DEBUG(DEBUG_INFO, "All IPC sockets created succesfully"); // Start UI Controller uiParams[0] = uiSockSet[WRITE]; threadResult += pthread_create(&controllers[0], NULL, UIController, (void*)uiParams); // ---------------------------- // Start Connection Manager conManParams[0] = connectionSockSet[WRITE]; threadResult += pthread_create(&controllers[1], NULL, ConnectionManager, (void*)conManParams); // ---------------------------- // Start the General Controller generalParams[0] = generalSockSet[READ]; generalParams[1] = out_gen[WRITE]; threadResult += pthread_create(&controllers[2], NULL, GeneralController, (void*)generalParams); // ---------------------------- // Start the Gameplay Controller gameplayParams[0] = gameplaySockSet[READ]; gameplayParams[1] = out_game[WRITE]; threadResult += pthread_create(&controllers[3], NULL, GameplayController, (void*)gameplayParams); // ---------------------------- // Start the Outbound Switchboard outboundParams[0] = out_in[READ]; outboundParams[1] = out_game[READ]; outboundParams[2] = out_gen[READ]; outboundParams[3] = out_keepal[READ]; threadResult += pthread_create(&controllers[4], NULL, OutboundSwitchboard, (void*)outboundParams); // ---------------------------- // Start the Keep Alive Cleaner keepAliveParams[0] = out_keepal[WRITE]; keepAliveParams[1] = keepAliveSockSet[WRITE]; threadResult += pthread_create(&controllers[5], NULL, KeepAlive, (void*)keepAliveParams); // ---------------------------- // Start the Movement Timer timerParams[0] = timerSockSet[WRITE]; threadResult += pthread_create(&controllers[6], NULL, MovementTimer, (void*)timerParams); // ---------------------------- // Start the Inbound Switchboard inboundParams[0] = generalSockSet[WRITE]; inboundParams[1] = gameplaySockSet[WRITE]; inboundParams[2] = uiSockSet[READ]; inboundParams[3] = out_in[WRITE]; inboundParams[4] = connectionSockSet[READ]; inboundParams[5] = keepAliveSockSet[READ]; inboundParams[6] = timerSockSet[READ]; threadResult += pthread_create(&controllers[7], NULL, InboundSwitchboard, (void*)inboundParams); // ---------------------------- if(threadResult<0){ fprintf(stderr, "One or more controllers failed to launch!\n Terminating."); // Kill all launched threads for(i = 0; i < NUM_CONTROLLERS; ++i){ pthread_kill(controllers[i], SIGKILL); } } else{ DEBUG(DEBUG_INFO, "All controllers launched"); // Wait on the inbound switchboard to terminate process pthread_join(controllers[6], NULL); } printf("%s\n%s\n\n", "-------------------------------------------------------------", " Server Terminated\n"); return 0; }
void ThreadImpl::terminate() { int ret = pthread_kill(_id, SIGKILL); if(ret != 0) throw SystemError("pthread_kill"); }
void kill(int sig) { assert(pthread_kill(native_, sig) == 0); }
int main() { int failed = 0; int i; HANDLE h[NUMTHREADS + 1]; unsigned thrAddr; /* Dummy variable to pass a valid location to _beginthreadex (Win98). */ for (i = 1; i <= NUMTHREADS; i++) { threadbag[i].started = 0; threadbag[i].threadnum = i; h[i] = (HANDLE) _beginthreadex(NULL, 0, Win32thread, (void *) &threadbag[i], 0, &thrAddr); } /* * Code to control or munipulate child threads should probably go here. */ Sleep(500); /* * Cancel all threads. */ for (i = 1; i <= NUMTHREADS; i++) { assert(pthread_kill(threadbag[i].self, 0) == 0); assert(pthread_cancel(threadbag[i].self) == 0); } /* * Give threads time to run. */ Sleep(NUMTHREADS * 100); /* * Standard check that all threads started. */ for (i = 1; i <= NUMTHREADS; i++) { if (!threadbag[i].started) { failed |= !threadbag[i].started; fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); } } assert(!failed); /* * Check any results here. Set "failed" and only print output on failure. */ failed = 0; for (i = 1; i <= NUMTHREADS; i++) { int fail = 0; int result = 0; assert(GetExitCodeThread(h[i], (LPDWORD) &result) == TRUE); //assert(threadbag[i].self->h != NULL); assert(pthread_kill(threadbag[i].self, 0) == ESRCH); fail = (result != (int) (size_t) PTHREAD_CANCELED); if (fail) { fprintf(stderr, "Thread %d: started %d: count %d\n", i, threadbag[i].started, threadbag[i].count); } failed = (failed || fail); } assert(!failed); /* * Success. */ return 0; }
Int main (Int argc, Char * argv []) { pid_t child_pid; pid_t child_sid; Int status = 0; Bool daemon = TRUE; Int o; Int i; Char * images [] = {NULL, NULL}; Int numImages = sizeof (images) / sizeof (images [0]); if (isDaemonRunning (argv [0])) { Osal_printf ("Multiple instances of syslink_daemon.out are not " "supported!\n"); return (-1); } /* Determine args */ while ((o = getopt (argc, argv, ":fs:a:")) != -1) { switch (o) { case 's': images [0] = optarg; break; case 'a': images [1] = optarg; break; case 'f': daemon = FALSE; break; case ':': status = -1; Osal_printf ("Option -%c requires an operand\n", optopt); break; case '?': status = -1; Osal_printf ("Unrecognized option: -%c\n", optopt); break; } } for (i = 0; optind < argc; optind++) { while (i < numImages && images [i]) i++; if (i == numImages) { printUsage (); } images [i++] = argv [optind]; } for (i = 0; i < numImages; i++) { if (images [i] && access (images [i], R_OK)) { Osal_printf ("Error opening %s\n", images [i]); printUsage (); } } if (status || optind < argc || !images [0]) { printUsage (); } /* Process will be daemonised if daemon flag is true */ if (daemon) { Osal_printf ("Spawning SysLink Daemon...\n"); /* Fork off the parent process */ child_pid = fork (); if (child_pid < 0) { Osal_printf ("Spawn daemon failed!\n"); exit (EXIT_FAILURE); /* Failure */ } /* If we got a good PID, then we can exit the parent process. */ if (child_pid > 0) { exit (EXIT_SUCCESS); /* Success */ } /* Change file mode mask */ umask (0); /* Create a new SID for the child process */ child_sid = setsid (); if (child_sid < 0) { exit (EXIT_FAILURE); /* Failure */ } /* Change the current working directory */ if ((chdir("/")) < 0) { exit (EXIT_FAILURE); /* Failure */ } } /* Setup the signal handlers */ if (signal (SIGINT, signal_handler) == SIG_ERR) { Osal_printf ("SIGINT registration failed!"); } if (signal (SIGTERM, signal_handler) == SIG_ERR) { Osal_printf ("SIGTERM registration failed!"); } while (restart) { restart = FALSE; isSysM3Event = FALSE; isAppM3Event = FALSE; sem_init (&semDaemonWait, 0, 0); status = ipcSetup (images [0], images [1]); if (status < 0) { Osal_printf ("ipcSetup failed!\n"); sem_destroy (&semDaemonWait); return (-1); } Osal_printf ("ipcSetup succeeded!\n"); /* Create the SysM3 fault handler thread */ Osal_printf ("Create SysM3 event handler thread\n"); status = pthread_create (&sysM3EvtHandlerThrd, NULL, (Void *)&sysM3EventHandler, NULL); if (status) { Osal_printf ("Error Creating SysM3 event handler thread:%d\n", status); ipcCleanup (); sem_destroy (&semDaemonWait); exit (EXIT_FAILURE); } /* Only if AppM3 image is specified */ if (images [1]) { /* Create an AppM3 fault handler thread */ Osal_printf ("Create AppM3 event handler thread\n"); status = pthread_create (&appM3EvtHandlerThrd, NULL, (Void *)&appM3EventHandler, NULL); if (status) { Osal_printf ("Error Creating AppM3 event handler thread:%d\n", status); pthread_kill (sysM3EvtHandlerThrd, SIGTERM); sysM3EvtHandlerThrd = 0; ipcCleanup (); sem_destroy (&semDaemonWait); exit (EXIT_FAILURE); } } /* Wait for any event handler thread to be unblocked */ sem_wait (&semDaemonWait); /* Clean up event handler threads */ if (sysM3EvtHandlerThrd) { if (isSysM3Event) { status = pthread_join (sysM3EvtHandlerThrd, NULL); Osal_printf ("pthread_join SysM3 Thread = %d\n", status); } else { if (pthread_kill (sysM3EvtHandlerThrd, SIGTERM) == 0) { status = pthread_join (sysM3EvtHandlerThrd, NULL); Osal_printf ("pthread_kill & join SysM3 Thread = %d\n", status); } } sysM3EvtHandlerThrd = 0; } if (appM3EvtHandlerThrd) { if (isAppM3Event) { status = pthread_join (appM3EvtHandlerThrd, NULL); Osal_printf ("pthread_join AppM3 Thread = %d\n", status); } else { if (pthread_kill (appM3EvtHandlerThrd, SIGTERM) == 0) { status = pthread_join (appM3EvtHandlerThrd, NULL); Osal_printf ("pthread_kill & join AppM3 Thread = %d\n", status); } } appM3EvtHandlerThrd = 0; } /* IPC_Cleanup function */ ipcCleanup (); sem_destroy (&semDaemonWait); } return 0; }
TEST(pthread, pthread_kill__invalid_signal) { ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1)); }
!(err = pthread_key_create(key, destructor)) && !(err2 = pthread_key_delete(*key)) ); if (!err && err2) err = -3; //meaning the dependecy failed WRAP_END } static int wrap_pthread_rwlock_unlock(pthread_rwlock_t *rwlock) { WRAP_START while (!err) err = pthread_rwlock_unlock(rwlock); WRAP_END } static int wrap_pthread_kill(pthread_t thread, int sig) { WRAP_START while(!err) err = pthread_kill(thread, sig); WRAP_END } /*static int wrap_pthread_equal(pthread_t t1, pthread_t t2) { WRAP_START do{ err = pthread_equal(t1, t2); }while(err != 0 && err != EINTR); WRAP_END }*/
inline void dyad::destory_thread() { pthread_kill(thread, 0); }
int modbus_main(int argc, char *argv[]) #endif { int option; int ret; /* Handle command line arguments */ g_modbus.quit = false; while ((option = getopt(argc, argv, "desqh")) != ERROR) { switch (option) { case 'd': /* Disable protocol stack */ (void)pthread_mutex_lock(&g_modbus.lock); g_modbus.threadstate = SHUTDOWN; (void)pthread_mutex_unlock(&g_modbus.lock); break; case 'e': /* Enable the protocol stack */ { ret = modbus_create_pollthread(); if (ret != OK) { fprintf(stderr, "modbus_main: " "ERROR: modbus_create_pollthread failed: %d\n", ret); exit(EXIT_FAILURE); } } break; case 's': /* Show current status */ switch (g_modbus.threadstate) { case RUNNING: printf("modbus_main: Protocol stack is running\n"); break; case STOPPED: printf("modbus_main: Protocol stack is stopped\n"); break; case SHUTDOWN: printf("modbus_main: Protocol stack is shutting down\n"); break; default: fprintf(stderr, "modbus_main: " "ERROR: Invalid thread state: %d\n", g_modbus.threadstate); break; } break; case 'q': /* Quit application */ g_modbus.quit = true; pthread_kill(g_modbus.threadid, 9); break; case 'h': /* Show help info */ modbus_showusage(argv[0], EXIT_SUCCESS); break; default: fprintf(stderr, "modbus_main: " "ERROR: Unrecognized option: '%c'\n", option); modbus_showusage(argv[0], EXIT_FAILURE); break; } } return EXIT_SUCCESS; }
/* Pause all threads in threadpool */ void thpool_pause(thpool_* thpool_p) { int n; for (n=0; n < thpool_p->num_threads_alive; n++){ pthread_kill(thpool_p->threads[n]->pthread, SIGUSR1); } }
gboolean mono_sgen_suspend_thread (SgenThreadInfo *info) { return pthread_kill (mono_thread_info_get_tid (info), suspend_signal_num) == 0; }
gboolean mono_sgen_resume_thread (SgenThreadInfo *info) { return pthread_kill (mono_thread_info_get_tid (info), restart_signal_num) == 0; }
void * threadGravite(void *) { int i, j, x, y; struct timespec observation, effet_graphique; observation.tv_sec = 2; observation.tv_nsec = 0; effet_graphique.tv_sec = 0; effet_graphique.tv_nsec = 500000000; while (1) { // On attend que toutes les analyses soient effectuées pthread_mutex_lock(&mutexAnalyse); while (nbAnalyses < pieceEnCours.nbCases) { pthread_cond_wait(&condAnalyse, &mutexAnalyse); } pthread_mutex_unlock(&mutexAnalyse); if (nbLignesCompletes == 0 && nbColonnesCompletes == 0) { printf("\n(GRAVITE) Rien d'intéressant dans ce move\n"); pthread_mutex_lock(&mutexAnalyse); nbAnalyses = 0; pthread_mutex_unlock(&mutexAnalyse); } else // Il fat supprimer des lignes/colonnes { printf("(GRAVITE) Gravité activée!\n"); printf("(GRAVITE) Suppression de %d lignes et %d colonnes:\n", nbLignesCompletes, nbColonnesCompletes); nanosleep(&observation, NULL); if (nbColonnesCompletes != 0) { // Tri des colonnes complètes afin de supprimer d'abbord les colonnes de gauche pthread_mutex_lock(&mutexAnalyse); qsort(colonnesCompletes, nbColonnesCompletes, sizeof(int), compare_ints); pthread_mutex_unlock(&mutexAnalyse); for (x = 0, y = 0 ; x < nbColonnesCompletes ; ++x) // Traitement pour chaque colonne complète { // Colonnes de gauche if (colonnesCompletes[x] < 5) { // Décalage des éléments vers la droite for (i = 0 ; i < NB_LIGNES ; ++i) { for (j = colonnesCompletes[x] ; j > 0 ; --j) { tab[i][j] = tab[i][j-1]; if (tab[i][j] == VIDE) EffaceCarre(i, j); else DessineSprite(i, j, tab[i][j]); } tab[i][0] = VIDE; EffaceCarre(i, 0); } ++y; // Y comptera le nombre de fois que nous avons traité des colonnes de gauche printf("Colonne %d supprimée.\n", colonnesCompletes[x]); } else // Colonnes de droite { // Décalage des éléments vers la gauche for (i = 0 ; i < NB_LIGNES ; ++i) { for (j = colonnesCompletes[nbColonnesCompletes-1-x + y] ; j < 9 ; ++j) { tab[i][j] = tab[i][j+1]; if (tab[i][j] == VIDE) EffaceCarre(i, j); else DessineSprite(i, j, tab[i][j]); } tab[i][9] = VIDE; EffaceCarre(i, 9); } printf("Colonne %d supprimée.\n", colonnesCompletes[nbColonnesCompletes-1-x + y]); } nanosleep(&effet_graphique, NULL); } } if (nbLignesCompletes != 0) { // Tri des lignes complètes afin de supprimer d'abbord les lignes du haut pthread_mutex_lock(&mutexAnalyse); qsort(lignesCompletes, nbLignesCompletes, sizeof(int), compare_ints); pthread_mutex_unlock(&mutexAnalyse); for (x = 0, y = 0 ; x < nbLignesCompletes ; ++x) // Traitement pour chaque ligne complète { // Lignes du haut if (lignesCompletes[x] < 7) { // Décalage des éléments vers le bas for (j = 0 ; j < 10 ; ++j) { for (i = lignesCompletes[x] ; i > 0 ; --i) { tab[i][j] = tab[i-1][j]; if (tab[i][j] == VIDE) EffaceCarre(i, j); else DessineSprite(i, j, tab[i][j]); } tab[0][j] = VIDE; EffaceCarre(0, j); } ++y; // Y Comptera le nombre de fois que l'on a traité des lignes en haut printf("Ligne %d supprimée.\n", lignesCompletes[x]); } else // Lignes du bas { // Décalage des éléments vers le haut for (j = 0 ; j < 10 ; ++j) { for (i = lignesCompletes[nbLignesCompletes-1-x+y] ; i < NB_LIGNES-1 ; ++i) { tab[i][j] = tab[i+1][j]; if (tab[i][j] == VIDE) EffaceCarre(i, j); else DessineSprite(i, j, tab[i][j]); } tab[NB_LIGNES-1][j] = VIDE; EffaceCarre(NB_LIGNES-1, j); } printf("Ligne %d supprimée.\n", lignesCompletes[nbLignesCompletes-1-x+y]); } nanosleep(&effet_graphique, NULL); } } // Ajout des points au score pthread_mutex_lock(&mutexScore); score += nbColonnesCompletes * COLONNE_COMPLETE; score += nbLignesCompletes * LIGNE_COMPLETE; MAJScore = 1; pthread_mutex_unlock(&mutexScore); pthread_cond_signal(&condScore); pthread_mutex_lock(&mutexAnalyse); nbColonnesCompletes = 0; nbLignesCompletes = 0; nbAnalyses = 0; pthread_mutex_unlock(&mutexAnalyse); } // Dans tous les cas: pthread_kill(threadHandleFinPartie, SIGUSR2); } }