Add SIGSTOP in SIGTSTP to properly stop the process.
[wsti_so.git] / src / process3.c
1 #include <stdio.h>
2
3 /* exit.. */
4 #include <stdlib.h>
5
6 /* open/read/write/close */
7 #include <fcntl.h>
8
9 /* Signals handling.. */
10 #include <signal.h>
11
12 /** Named pipe used to communicate with process2 */
13 char * read_pipe = "/tmp/process2pipe";
14
15 /** Descriptor of input pipe */
16 int read_descriptor;
17
18 /**
19  * Handler for signals.
20  */
21 void sig_handler(int signo)
22 {
23         fprintf(stderr, "[%s] Received %s!\n", "process3", strsignal(signo));
24         if (signo == SIGUSR1) {
25         }
26         else if (signo == SIGTERM) {
27                 fprintf(stderr, "[%s] > Releasing resources\n", "process3");
28                 close(read_descriptor);
29                 exit(0);
30         }
31         else if (signo == SIGTSTP) {
32                 fprintf(stderr, "[%s] > Closing pipe\n", "process3");
33                 close(read_descriptor);
34                 raise (SIGSTOP);
35         }
36         else if (signo == SIGCONT) {
37                 fprintf(stderr, "[%s] > Opening pipe\n", "process3");
38                 read_descriptor = open(read_pipe, O_RDONLY);
39         }
40 }
41
42 /**
43  * Program grabs data (calculated number of characters) from process2 and prints
44  * grabbed data to the standard output.
45  */
46 int main(void) {
47         /** Buffer used for storing data from input pipe */
48         int buffer = 0;
49         
50         /** Stores number of bytes read from input pipe in current iteration */
51         ssize_t count = 0;
52
53         fprintf(stderr, "[%s] Init!\n", "process3");
54
55         /**
56          * Register signals handled by process
57          */
58         if (signal(SIGUSR1, sig_handler) == SIG_ERR) {
59                 fprintf(stderr, "can't catch SIGUSR1\n");
60         }
61         if (signal(SIGTERM, sig_handler) == SIG_ERR) {
62                 fprintf(stderr, "can't catch SIGTERM\n");
63         }
64         if (signal(SIGTSTP, sig_handler) == SIG_ERR) {
65                 fprintf(stderr, "can't catch SIGTSTP\n");
66         }
67         if (signal(SIGCONT, sig_handler) == SIG_ERR) {
68                 fprintf(stderr, "can't catch SIGCONT\n");
69         }
70
71         /* Reading from process2 */
72         read_descriptor = open(read_pipe, O_RDONLY);
73
74         while(1) {
75                 /* Read data from input pipe */
76                 count = read(read_descriptor, &buffer, sizeof(int));
77
78                 fprintf(stderr, "[%s] Fetched: %d bytes\n", "process3", count);
79
80                 if (count > 0) {
81                         fprintf(stderr, "[%s] Process2 send: %d\n", "process3", buffer);
82                 }
83                 else {
84                         break;
85                 }
86         }
87
88         /* Release resources in normal program flow exit. */
89         close(read_descriptor);
90
91         return 0;
92 }