Working communication using pipes.
[wsti_so.git] / src / process2.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 /* open/read/write/close */
6 #include <fcntl.h>
7
8 /** If buffer is too small to hold entire string, it is incremented by this value */
9 #define BUFFER_STEP 16
10
11 /**
12  * Program grabs data from process1, calculates number of characters in each line
13  * and pass the value to process3.
14  */
15 int main(void) {
16         /** Named pipe used to communicate with process1 */
17         char * read_pipe = "/tmp/process1pipe";
18
19         /** Named pipe used to communicate with process3 */
20         char * write_pipe = "/tmp/process2pipe";
21
22         int read_descriptor;
23         int write_descriptor;
24         
25         char buffer[BUFFER_STEP];
26         
27         int i = 0;
28         ssize_t count = 0;
29
30         /* Reading from process1 */
31         read_descriptor = open(read_pipe, O_RDONLY);
32
33         /* Writing to process2 */
34         mkfifo(write_pipe, 0666);
35         write_descriptor = open(write_pipe, O_WRONLY);
36
37         int number_of_characters = 0;
38         
39         while(1) {
40                 /* Read data from input pipe */
41                 count = read(read_descriptor, buffer, BUFFER_STEP);
42
43                 fprintf(stderr, "[%s] Fetched: %d bytes\n", "process2", count);
44
45                 if (count > 0) {
46                         for (i = 0; i < count; i++, number_of_characters++) {
47                                 if (buffer[i] == '\n') {
48                                         fprintf(stderr, "[%s] Calculated: %d characters. Sending...\n", "process2", number_of_characters);
49                                         write(write_descriptor, &number_of_characters, sizeof(number_of_characters));
50                                         write(write_descriptor, '\n', 1);
51                                         number_of_characters = 0;
52                                 }
53                         }
54                 }
55                 else {
56                         break;
57                 }
58         }
59
60         close(read_descriptor);
61         close(write_descriptor);
62         unlink(write_descriptor);
63
64         return 0;
65 }