Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #define MAXSIZE 10
- int main(int argc, char *argv[])
- {
- int i;
- int p2c[2];
- int child2p[2];
- int val = 0;
- int val2 = 0;
- int threecount = 0;
- int fivecount = 0;
- // create pipe descriptors
- pipe(p2c);
- pipe(child2p);
- // fork() returns 0 for child process, child-pid for parent process.
- if (fork() != 0)
- {
- // parent: writing only, so close read-descriptor.
- close(p2c[0]);
- // parent: reading only, so close write descriptor
- close(child2p[1]);
- for(i = 0; i < MAXSIZE; i++)
- {
- // send the value on the write-descriptor to the child.
- if(i % 5 == 0)
- {
- fivecount++;
- }
- else
- {
- write(p2c[1],&i, sizeof(i));
- printf("Parent(%d) send value: %d\n", getpid(), i);
- }
- }
- // read from the child
- // close the write descriptor
- close(p2c[1]);
- read(child2p[0], &threecount,sizeof(threecount));
- printf("Parent(%d) received value: %d for threecount and has %d for fivecount.\n", getpid(), threecount, fivecount);
- wait();
- // close the read descriptor from the child
- close(child2p[0]);
- }
- else
- { // child: reading only, so close the write-descriptor
- close(p2c[1]);
- // child: writing only, so close the read descriptor
- close(child2p[0]);
- // now read the data from parent(will block)
- while (read(p2c[0], &i, sizeof(i))){
- printf("Child(%d) received value: %d\n", getpid(), i);
- if(i % 3 == 0)
- {
- threecount++;
- }
- }
- // send to the
- write(child2p[1], &threecount, sizeof(threecount));
- printf("Child(%d) sendvalue: %d\n", getpid(), threecount);
- // close the read-descriptor
- close(p2c[0]);
- // close the write-descriptor
- close(child2p[1]);
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment