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