Advertisement
Guest User

Untitled

a guest
Jan 18th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <ctype.h>
  6. #include <sys/wait.h>
  7.  
  8. void kill_process() {
  9. printf("\nZamykanie programu...\n");
  10. exit(0);
  11. }
  12.  
  13. int main(void) {
  14. int pp1 = 0, pp2 = 0, pipe1[2], pipe2[2], pipe3[2], pipe4[2];
  15. char buf, end = 8;
  16. _Bool receiving = 0;
  17. pipe(pipe1);
  18. pipe(pipe2);
  19. pipe(pipe3);
  20. pipe(pipe4);
  21.  
  22. if ((pp1 = fork())) {
  23. if ((pp2 = fork())) {
  24. signal(SIGTERM, kill_process);
  25. // parent
  26. close(pipe1[1]);
  27. close(pipe2[0]);
  28. close(pipe3[1]);
  29. close(pipe4[0]);
  30. while (read(pipe1[0], &buf, 1) > 0) {
  31. if (!receiving)
  32. printf("1. PM:%i\n", getpid());
  33. receiving = 1;
  34. write(pipe2[1], &buf, 1);
  35. if (buf == end) {
  36. receiving = 0;
  37. while (read(pipe3[0], &buf, 1) > 0) {
  38. if (!receiving)
  39. printf("3. PM:%i\n", getpid());
  40. receiving = 1;
  41. write(pipe4[1], &buf, 1);
  42. if (buf == end) {
  43. receiving = 0;
  44. break;
  45. }
  46. }
  47. }
  48. }
  49. close(pipe1[0]);
  50. wait(NULL);
  51. exit(EXIT_SUCCESS);
  52. } else {
  53. // pp2
  54. close(pipe2[1]);
  55. close(pipe3[0]);
  56. while (read(pipe2[0], &buf, 1) > 0) {
  57. if (!receiving)
  58. printf("2. PP2:%i\n", getpid());
  59. receiving = 1;
  60. buf = tolower(buf);
  61. write(pipe3[1], &buf, 1);
  62. if (buf == end)
  63. receiving = 0;
  64. }
  65. }
  66. } else {
  67. // pp1
  68. close(pipe1[0]);
  69. close(pipe4[1]);
  70. char str[100] = "";
  71. while (1) {
  72. scanf("%s", str);
  73. if (strcmp("q", str) == 0) {
  74. kill(getppid(), SIGTERM);
  75. break;
  76. };
  77. write(pipe1[1], str, strlen(str));
  78. write(pipe1[1], &end, 1);
  79. while (read(pipe4[0], &buf, 1) > 0) {
  80. if (!receiving)
  81. printf("4. PP1:%i\n", getpid());
  82. receiving = 1;
  83. write(STDOUT_FILENO, &buf, 1);
  84. if (buf == end) {
  85. receiving = 0;
  86. write(STDOUT_FILENO, "\n", 1);
  87. break;
  88. }
  89. }
  90. }
  91. close(pipe1[1]);
  92. close(pipe4[0]);
  93. exit(0);
  94. }
  95.  
  96. return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement