Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. // C program to demonstrate use of fork() and pipe()
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<unistd.h>
  5. #include<sys/types.h>
  6. #include<string.h>
  7. #include<sys/wait.h>
  8.  
  9. int main(int argc, char **argv)
  10. {
  11. if (argc < 3) {
  12. printf("Error: This program requires at least 2 arguments\n");
  13. exit(0);
  14. }
  15. int cNum = atoi(argv[1]);
  16. int offset = 2;
  17. int inputLen = argc - offset;
  18. printf("There are %i children\n", cNum);
  19. // We use two pipes
  20. // First pipe to send input string from parent
  21. // Second pipe to send concatenated string from child
  22. int pipes[cNum][2]; // Used to store two ends of first pipe
  23.  
  24. char fixed_str[] = "forgeeks.org";
  25. char input_str[100];
  26. pid_t p;
  27.  
  28. for(int i = 0; i < cNum; i++) {
  29. if (pipe(pipes[i])==-1)
  30. {
  31. fprintf(stderr, "Pipe Failed" );
  32. return 1;
  33. }
  34. }
  35.  
  36. int final = 0;
  37. for (int i = 0; i < cNum; i++) {
  38. p = fork();
  39. if (p < 0)
  40. {
  41. fprintf(stderr, "fork Failed" );
  42. return 1;
  43. }
  44.  
  45. // Parent process
  46. else if (p > 0)
  47. {
  48. wait(NULL);
  49. close(pipes[i][1]); // Close writing end of second pipe
  50. // Read string from child, print it and close
  51. // reading end.
  52. char readval[20] = { 0 };
  53. read(pipes[i][0], readval, 20);
  54. printf("Read value %s\n", readval);
  55. final += atoi(readval);
  56. close(pipes[i][0]);
  57. }
  58. // child process
  59. else
  60. {
  61. // Close both reading ends
  62. close(pipes[i][0]);
  63. int total = 0;
  64. for (int j = 0; j < inputLen; j++) {
  65. if (j % cNum == i){
  66. total += atoi(argv[offset + j]);
  67. }
  68. }
  69. printf("Child %i got total %i\n", i, total);
  70. // Write concatenated string and close writing end
  71. char str[10] = { 0 };
  72. sprintf(str, "%i", total);
  73. printf("Data to write for child %i is %s\n", i, str);
  74. write(pipes[i][1], str, strlen(str));
  75. close(pipes[i][1]);
  76. exit(0);
  77. }
  78. }
  79.  
  80. printf("Parent calculated %i as total\n", final);
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement