Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <inttypes.h>
  3. #include <fcntl.h>
  4. #include <stdlib.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7. #include <unistd.h>
  8.  
  9. int main(int argc, char ** argv) {
  10. int n = (int) strtol(argv[1], NULL, 10), cur_n = 0;
  11. int filedes_1[2];
  12. pipe(filedes_1);
  13. int filedes_2[2];
  14. pipe(filedes_2);
  15. FILE *output_1 = fdopen(filedes_1[1], "w");
  16. FILE *output_2 = fdopen(filedes_2[1], "w");
  17. fprintf(output_2, "1 ");
  18. fflush(output_2);
  19. pid_t child_1 = fork();
  20. if (child_1 == 0) {
  21. FILE * input = fdopen(filedes_2[0], "r");
  22. close(filedes_1[0]);
  23. close(filedes_2[1]);
  24. while (fscanf(input, "%d", &cur_n) != EOF) {
  25. if (cur_n == n) {
  26. _exit(0);
  27. }
  28. printf("1 ");
  29. printf("%d\n", cur_n);
  30. fprintf(output_1, "%d ", ++cur_n);
  31. fflush(stdout);
  32. fflush(output_1);
  33. }
  34. close(filedes_1[1]);
  35. close(filedes_2[0]);
  36. fclose(input);
  37. fclose(output_1);
  38. _exit(0);
  39. }
  40. pid_t child_2 = fork();
  41. if (child_2 == 0) {
  42. FILE * input = fdopen(filedes_1[0], "r");
  43. close(filedes_1[1]);
  44. close(filedes_2[0]);
  45. while (fscanf(input, "%d", &cur_n) != EOF) {
  46. if (cur_n == n) {
  47. _exit(0);
  48. }
  49. printf("2 ");
  50. printf("%d\n", cur_n);
  51. fprintf(output_2, "%d ", ++cur_n);
  52. fflush(stdout);
  53. fflush(output_2);
  54. }
  55. close(filedes_1[0]);
  56. close(filedes_2[1]);
  57. fclose(input);
  58. fclose(output_2);
  59. _exit(0);
  60. }
  61. close(filedes_1[0]);
  62. close(filedes_1[1]);
  63. close(filedes_2[0]);
  64. close(filedes_2[1]);
  65. wait(NULL);
  66. wait(NULL);
  67. printf("Done\n");
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement