/* signal_test.c * * This is a simple little piece of sample code that shows how to * use signals and how to implement a function that mimics the * unix behaviour of using -pid to send a signal to the entire process * group. As beos threads/team don't really match the structure found on * unix boxes this is a hack. * * Build using * * gcc -Wall -g -O0 -o signal_test signal_test.c * */ #include #include #include #define THREADS 20 static int ok_to_exit = 0; void deliver_signal(thread_id id, uint sig) { if (id < 0) { thread_info ti; int32 cookie = 0; while (get_next_thread_info(0, &cookie, &ti) == B_OK) { if (ti.thread != find_thread(NULL)) kill(ti.thread, sig); } } else kill(id, sig); } void tell_us(int sig) { printf("thread %6ld got a signal...", find_thread(NULL)); switch (sig) { case SIGHUP: printf("HUP\n"); break; case SIGTERM: printf("TERM\n"); ok_to_exit = 1; break; default: printf("%d\n", sig); break; } } int32 test_thread(void *data) { struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = tell_us; sigaction(SIGHUP, &sa, NULL); sigaction(SIGTERM, &sa, NULL); while (1) { snooze(100000); if (ok_to_exit) break; } printf("thread %6ld exiting\n", find_thread(NULL)); return 0; } int main(int argc, char **argv) { thread_id threads[THREADS]; status_t exit_code; int i; for (i=0; i < THREADS; i++) { threads[i] = spawn_thread(test_thread, "test", B_NORMAL_PRIORITY, NULL); if (threads[i] > 0) resume_thread(threads[i]); } printf("started %d threads\n", THREADS); printf("signalling HUP to thread %6ld -> ", threads[0]); kill(threads[0], SIGHUP); printf("signalling HUP to thread -%6ld -> ", threads[0]); send_signal(-threads[0], SIGHUP); printf("\n"); printf("delivering HUP to thread -%6ld -> \n", threads[0]); deliver_signal(-threads[0], SIGHUP); printf("\n"); printf("signalling HUP to thread %6ld -> ", threads[0]); kill(threads[0], SIGHUP); kill(threads[0], SIGTERM); printf("Waiting for last thread to die...\n"); wait_for_thread(threads[THREADS - 1], &exit_code); printf("Complete.\n"); return 0; }