How to write a C Program for Pipes Exercise in C Programming Language ?
Solution:
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #include <unistd.h>
- int main(int argc, char **argv)
- {
- int n;
- int i, pid, sum = 0;
- int fd[2];
- if( (argc != 2) || (sscanf(argv[1],"%d",&n) != 1) )
- {
- fprintf(stderr, "I need just one parameter and that's a number\n");
- exit(1);
- }
- if(pipe(fd))
- {
- // pipe != 0 -> something went wrong
- fprintf(stderr, "\nI am not a plumber, I am not able to make a pipe\n");
- exit(1);
- }
- // set stdout buf to null to get ordered output
- setbuf(stdout, NULL);
- // make n children
- for(i = 0 ; i<n ; i++)
- {
- // i-th child
- if((pid=fork()) == 0)
- {
- // I'm not reading anything,
- // so close the read side of the pipe
- close(fd[0]);
- // compute the power
- n = pow(2, i);
- printf("I'm %d computing 2^%d = %d\n", i , i , n);
- write(fd[1], &n, sizeof(int));
- // close the pipe on the write side,
- // so the parent will get -1 when non more data are available
- // and the write side of the pipe has been closed by all children
- close(fd[1]);
- exit(0);
- }
- // something went wrong
- else if(pid < 0)
- {
- fprintf(stderr, "I am sterile, I can't have children\n");
- exit(1);
- }
- }
- // the parent closes the write side of the pipe
- close(fd[1]);
- while(read(fd[0], &i, sizeof(int) )>0)
- {
- printf("SUM: %d\tValue: %d\n", sum, i);
- sum+=i;
- }
- // finally it closes the other side too
- close(fd[0]);
- printf("\n%d\n", sum);
- return 0;
- }