chore: fix almost *ALL* warnings.
[lunaix-os.git] / lunaix-os / uprog / signal_demo.c
1 #include <signal.h>
2 #include <stdio.h>
3 #include <sys/lunaix.h>
4 #include <unistd.h>
5
6 void
7 sigchild_handler(int signum)
8 {
9     printf("SIGCHLD received\n");
10 }
11
12 void
13 sigsegv_handler(int signum)
14 {
15     pid_t pid = getpid();
16     printf("SIGSEGV received on process %d\n", pid);
17     _exit(signum);
18 }
19
20 void
21 sigalrm_handler(int signum)
22 {
23     pid_t pid = getpid();
24     printf("I, pid %d, have received an alarm!\n", pid);
25 }
26
27 void
28 main()
29 {
30     signal(SIGCHLD, sigchild_handler);
31     signal(SIGSEGV, sigsegv_handler);
32     signal(SIGALRM, sigalrm_handler);
33
34     alarm(5);
35
36     int status;
37     pid_t p = 0;
38
39     printf("Child sleep 3s, parent pause.\n");
40     if (!fork()) {
41         sleep(3);
42         _exit(0);
43     }
44
45     pause();
46
47     printf("Parent resumed on SIGCHILD\n");
48
49     for (int i = 0; i < 5; i++) {
50         pid_t pid = 0;
51         if (!(pid = fork())) {
52             signal(SIGSEGV, sigsegv_handler);
53             sleep(i);
54             if (i == 3) {
55                 i = *(int*)0xdeadc0de; // seg fault!
56             }
57             printf("%d\n", i);
58             _exit(0);
59         }
60         printf("Forked %d\n", pid);
61     }
62
63     while ((p = wait(&status)) >= 0) {
64         short code = WEXITSTATUS(status);
65         if (WIFSIGNALED(status)) {
66             printf("Process %d terminated by signal, exit_code: %d\n", p, code);
67         } else if (WIFEXITED(status)) {
68             printf("Process %d exited with code %d\n", p, code);
69         } else {
70             printf("Process %d aborted with code %d\n", p, code);
71         }
72     }
73
74     printf("done\n");
75 }