· 6 years ago · Sep 15, 2019, 05:30 PM
1//Note: pipes are not bi-directional, so you will need two pipes per process, one for receiving (reading) and one for sending (writing). if you the to send (write) something using pipe1 you need to close the reading end of that pipe, namely close(pipe1[0]). In the same way, if you need to receive something from the someone, you have to use another pipe, let say pipe2, so you use the reading end part and close the writing end, namely close(pipe2[1]) */
2
3//Sorry for any typo, I hope that this code will help you to beeter understand, how to use the API for process. Feel free to extend this code for two and three childrens.
4
5#include <stdlib.h>
6#include <stdio.h>
7#include <unistd.h>
8#include <sys/types.h>
9
10int main(int argv, char** argc) {
11 // initialize pipes
12 int p1[2];
13 int p2[2];
14 pipe(p1);
15 pipe(p2);
16 int luis;
17
18 int numElements = 6; //num of elements in the array
19 luis = fork(); //creating a child
20
21 if (luis == 0) { // If I am the child read the elements of the array that my parent sent me
22
23 close(p1[1]); //closing the writing end of pipe1 (p1), I am using p1 for reading so p1[0] is open for reading from my parent
24 close(p2[0]); //closing the reading end of pipe2 (p2), I am using p2 for sending (writing) the sumation to my parent
25 int vals[numElements];
26 read(p1[0], &vals, sizeof(vals));
27
28 // compute the sum
29 int sum = 0;
30 printf("child %d: received ", getpid()); //printing my pid and the array that I just received from my parent
31 int i;
32 for (i=0;i<numElements;i++){
33 printf("%d, ", vals[i]);
34 sum += vals[i]; //Adding the elments of the array
35 }
36 printf("\n");
37 printf("child %d: sending %d to parent\n", getpid(), sum);
38 // send result to parent
39 write(p2[1], &sum, sizeof(sum)); //sending to the parent the sum of the array
40 exit(0); //key line of code.
41 } else {
42 // parent
43 close(p1[0]); //closing reading, because I will use pipe1 for sending info to my child
44 close(p2[1]); //closing writing, bacuase I will use this pipe2 for receiving the summation from my child
45 // send values to child
46 int valsToSend[6] = {2,3,7,-1,10,6};
47 write(p1[1], &valsToSend, sizeof(valsToSend));
48 printf("parent is %d\n", getpid());
49 // receive and print the final value
50 int recval;
51 read(p2[0], &recval, sizeof(recval));
52 printf("parent: final sum is %d\n", recval);
53 exit(0);
54 }
55 return 0;
56}