Advertisement
anechka_ne_plach

Untitled

Apr 14th, 2022
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.54 KB | None | 0 0
  1. 1 │ #include <sys/types.h>
  2. 2 │ #include <sys/wait.h>
  3. 3 │ #include <unistd.h>
  4. 4 │ #include <stdio.h>
  5. 5 │ #include <stdlib.h>
  6. 6 │
  7. 7 │ int main(int argc, char* argv[]) {
  8. 8 │ int fds[2];
  9. 9 │ pipe(fds);
  10. 10 │
  11. 11 │ int pid1 = fork();
  12. 12 │ if (!pid1) {
  13. 13 │ close(fds[1]);
  14. 14 │ int pid2 = fork();
  15. 15 │ if (!pid2) {
  16. 16 │ int v;
  17. 17 │ long long sum = 0;
  18. 18 │ while (read(fds[0], &v, sizeof(v))) {
  19. 19 │ sum += v;
  20. 20 │ }
  21. 21 │ close(fds[0]);
  22. 22 │ printf("%lld\n", sum);
  23. 23 │ fflush(stdout);
  24. 24 │ _exit(0);
  25. 25 │ }
  26. 26 │ close(fds[0]);
  27. 27 │ while (wait(NULL) > 0);
  28. 28 │ _exit(0);
  29. 29 │ }
  30. 30 │ close(fds[0]);
  31. 31 │
  32. 32 │ int v = 0;
  33. 33 │ while (scanf("%d", &v) > 0) {
  34. 34 │ write(fds[1], &v, sizeof(v));
  35. 35 │ }
  36. 36 │ close(fds[1]);
  37. 37 │ while (wait(NULL) > 0);
  38. 38 │ return 0;
  39. 39 │ }
  40.  
  41. 1 │ #include <sys/types.h>
  42. 2 │ #include <sys/wait.h>
  43. 3 │ #include <unistd.h>
  44. 4 │ #include <stdio.h>
  45. 5 │ #include <stdlib.h>
  46. 6 │ #include <fcntl.h>
  47. 7 │
  48. 8 │ int main(int argc, char* argv[]) {
  49. 9 │ if (argc != 2) {
  50. 10 │ return 1;
  51. 11 │ }
  52. 12 │
  53. 13 │ int n = strtol(argv[1], NULL, 10) - 1;
  54. 14 │
  55. 15 │ int fds[2][2];
  56. 16 │ pipe(fds[0]);
  57. 17 │ pipe(fds[1]);
  58. 18 │
  59. 19 │ for (int t = 1; t <= 2; ++t) {
  60. 20 │ int pid = fork();
  61. 21 │ int fdr = fds[t == 1][0];
  62. 22 │ int fdw = fds[t == 2][1];
  63. 23 │ if (!pid) {
  64. 24 │ FILE* file1 = fdopen(fdr, "r");
  65. 25 │ FILE* file2 = fdopen(fdw, "w");
  66. 26 │ if (n != 0) {
  67. 27 │ if (t == 1) {
  68. 28 │ printf("1 1\n");
  69. 29 │ fflush(stdout);
  70. 30 │ fprintf(file2, "1\n");
  71. 31 │ fflush(file2);
  72. 32 │ }
  73. 33 │ if (n != 1) {
  74. 34 │ int value;
  75. 35 │ for (;;) {
  76. 36 │ fscanf(file1, "%d", &value);
  77. 37 │ if (value == n) break;
  78. 38 │ ++value;
  79. 39 │ printf("%d %d\n", t, value);
  80. 40 │ fflush(stdout);
  81. 41 │ fprintf(file2, "%d\n", value);
  82. 42 │ fflush(file2);
  83. 43 │ if (value == n) break;
  84. 44 │ }
  85. 45 │ }
  86. 46 │ }
  87. 47 │ if (t == 1) {
  88. 48 │ close(fds[t == 2][0]);
  89. 49 │ close(fds[t == 1][1]);
  90. 50 │ }
  91. 51 │ fclose(file1);
  92. 52 │ fclose(file2);
  93. 53 │ exit(0);
  94. 54 │ }
  95. 55 │ close(fdr);
  96. 56 │ close(fdw);
  97. 57 │ }
  98. 58 │ while (wait(NULL) > 0);
  99. 59 │ printf("Done\n");
  100. 60 │ fflush(stdout);
  101. 61 │ return 0;
  102. 62 │ }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement