xref: /libuv/docs/code/signal/main.c (revision d59d6e6f)
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <uv.h>
5 
create_loop()6 uv_loop_t* create_loop()
7 {
8     uv_loop_t *loop = malloc(sizeof(uv_loop_t));
9     if (loop) {
10       uv_loop_init(loop);
11     }
12     return loop;
13 }
14 
signal_handler(uv_signal_t * handle,int signum)15 void signal_handler(uv_signal_t *handle, int signum)
16 {
17     printf("Signal received: %d\n", signum);
18     uv_signal_stop(handle);
19 }
20 
21 // two signal handlers in one loop
thread1_worker(void * userp)22 void thread1_worker(void *userp)
23 {
24     uv_loop_t *loop1 = create_loop();
25 
26     uv_signal_t sig1a, sig1b;
27     uv_signal_init(loop1, &sig1a);
28     uv_signal_start(&sig1a, signal_handler, SIGUSR1);
29 
30     uv_signal_init(loop1, &sig1b);
31     uv_signal_start(&sig1b, signal_handler, SIGUSR1);
32 
33     uv_run(loop1, UV_RUN_DEFAULT);
34 }
35 
36 // two signal handlers, each in its own loop
thread2_worker(void * userp)37 void thread2_worker(void *userp)
38 {
39     uv_loop_t *loop2 = create_loop();
40     uv_loop_t *loop3 = create_loop();
41 
42     uv_signal_t sig2;
43     uv_signal_init(loop2, &sig2);
44     uv_signal_start(&sig2, signal_handler, SIGUSR1);
45 
46     uv_signal_t sig3;
47     uv_signal_init(loop3, &sig3);
48     uv_signal_start(&sig3, signal_handler, SIGUSR1);
49 
50     while (uv_run(loop2, UV_RUN_NOWAIT) || uv_run(loop3, UV_RUN_NOWAIT)) {
51     }
52 }
53 
main()54 int main()
55 {
56     printf("PID %d\n", getpid());
57 
58     uv_thread_t thread1, thread2;
59 
60     uv_thread_create(&thread1, thread1_worker, 0);
61     uv_thread_create(&thread2, thread2_worker, 0);
62 
63     uv_thread_join(&thread1);
64     uv_thread_join(&thread2);
65     return 0;
66 }
67