5 /* open/read/write/close */
8 /* Signals handling.. */
11 /** If buffer is too small to hold entire string, it is incremented by this value */
12 #define BUFFER_STEP 16
14 /** Named pipe used to communicate with process1 */
15 char * read_pipe = "/tmp/process1pipe";
17 /** Named pipe used to communicate with process3 */
18 char * write_pipe = "/tmp/process2pipe";
20 /** Descriptor of input pipe */
23 /** Descriptor of output pipe */
27 * Handler for signals.
29 void sig_handler(int signo)
31 fprintf(stderr, "[%s] Received %s!\n", "process2", strsignal(signo));
32 if (signo == SIGUSR1) {
34 else if (signo == SIGTERM) {
35 fprintf(stderr, "[%s] > Releasing resources\n", "process2");
36 close(read_descriptor);
37 close(write_descriptor);
38 unlink(write_descriptor);
41 else if (signo == SIGTSTP) {
42 fprintf(stderr, "[%s] > Closing pipes\n", "process2");
43 close(read_descriptor);
44 close(write_descriptor);
47 else if (signo == SIGCONT) {
48 fprintf(stderr, "[%s] > Opening pipes\n", "process2");
49 read_descriptor = open(read_pipe, O_RDONLY);
50 write_descriptor = open(write_pipe, O_WRONLY);
55 * Program grabs data from process1, calculates number of characters in each line
56 * and pass the value to process3.
60 * Buffer used for storing data from input pipe.
61 * Data is stored in chunks of BUFFER_STEP size.
62 * If data during reading is bigger than this value, then number of
63 * characters is saved, and buffer is cleared for reading another chunk.
65 char buffer[BUFFER_STEP];
67 /** Index used when iterating buffer */
70 /** Stores number of bytes read from input pipe in current iteration */
73 int number_of_characters = 0;
75 fprintf(stderr, "[%s] Init!\n", "process2");
78 * Register signals handled by process
80 if (signal(SIGUSR1, sig_handler) == SIG_ERR) {
81 fprintf(stderr, "can't catch SIGUSR1\n");
83 if (signal(SIGTERM, sig_handler) == SIG_ERR) {
84 fprintf(stderr, "can't catch SIGTERM\n");
86 if (signal(SIGTSTP, sig_handler) == SIG_ERR) {
87 fprintf(stderr, "can't catch SIGTSTP\n");
89 if (signal(SIGCONT, sig_handler) == SIG_ERR) {
90 fprintf(stderr, "can't catch SIGCONT\n");
93 /* Reading from process1 */
94 read_descriptor = open(read_pipe, O_RDONLY);
96 /* Writing to process2 */
97 mkfifo(write_pipe, 0666);
98 write_descriptor = open(write_pipe, O_WRONLY);
101 /* Read data from input pipe */
102 count = read(read_descriptor, buffer, BUFFER_STEP);
104 fprintf(stderr, "[%s] Fetched: %d bytes\n", "process2", count);
107 for (i = 0; i < count; i++, number_of_characters++) {
108 if (buffer[i] == '\n') {
109 fprintf(stderr, "[%s] Calculated: %d characters. Sending...\n", "process2", number_of_characters);
110 write(write_descriptor, &number_of_characters, sizeof(number_of_characters));
111 write(write_descriptor, '\n', 1);
112 number_of_characters = 0;
121 /* Release resources in normal program flow exit. */
122 close(read_descriptor);
123 close(write_descriptor);
124 unlink(write_descriptor);