Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // C program to demonstrate use of fork() and pipe()
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<sys/types.h>
- #include<string.h>
- #include<sys/wait.h>
- int main(int argc, char **argv)
- {
- if (argc < 3) {
- printf("Error: This program requires at least 2 arguments\n");
- exit(0);
- }
- int cNum = atoi(argv[1]);
- int offset = 2;
- int inputLen = argc - offset;
- printf("There are %i children\n", cNum);
- // We use two pipes
- // First pipe to send input string from parent
- // Second pipe to send concatenated string from child
- int pipes[cNum][2]; // Used to store two ends of first pipe
- char fixed_str[] = "forgeeks.org";
- char input_str[100];
- pid_t p;
- for(int i = 0; i < cNum; i++) {
- if (pipe(pipes[i])==-1)
- {
- fprintf(stderr, "Pipe Failed" );
- return 1;
- }
- }
- int final = 0;
- for (int i = 0; i < cNum; i++) {
- p = fork();
- if (p < 0)
- {
- fprintf(stderr, "fork Failed" );
- return 1;
- }
- // Parent process
- else if (p > 0)
- {
- wait(NULL);
- close(pipes[i][1]); // Close writing end of second pipe
- // Read string from child, print it and close
- // reading end.
- char readval[20] = { 0 };
- read(pipes[i][0], readval, 20);
- printf("Read value %s\n", readval);
- final += atoi(readval);
- close(pipes[i][0]);
- }
- // child process
- else
- {
- // Close both reading ends
- close(pipes[i][0]);
- int total = 0;
- for (int j = 0; j < inputLen; j++) {
- if (j % cNum == i){
- total += atoi(argv[offset + j]);
- }
- }
- printf("Child %i got total %i\n", i, total);
- // Write concatenated string and close writing end
- char str[10] = { 0 };
- sprintf(str, "%i", total);
- printf("Data to write for child %i is %s\n", i, str);
- write(pipes[i][1], str, strlen(str));
- close(pipes[i][1]);
- exit(0);
- }
- }
- printf("Parent calculated %i as total\n", final);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement