Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5. #include <inttypes.h>
  6. #include <stdint.h>
  7. #include <fcntl.h>
  8.  
  9. int pingpong(int fdr, int fdw, int id, int max_num){
  10. while (1) {
  11. int x;
  12. if (read(fdr, &x, sizeof(x)) == 0) {
  13. return(0);
  14. }
  15. printf("%d %d\n", id, x);
  16. fflush(stdout);;
  17. ++x;
  18. if (x == max_num) {
  19. return(0);
  20. }
  21. write(fdw, &x, sizeof(x));
  22. }
  23. }
  24.  
  25. int main(int argc, char **argv)
  26. {
  27. int max_num = strtol(argv[1], NULL, 10);
  28. if (max_num <= 1) {
  29. _exit(0);
  30. }
  31. int fd12[2];
  32. int fd21[2];
  33. if (pipe(fd12) < 0) {
  34. perror("pipe");
  35. _exit(1);
  36. }
  37. if (pipe(fd21) < 0) {
  38. perror("pipe");
  39. _exit(1);
  40. }
  41. int pid1, pid2;
  42. if ((pid1 = fork()) < 0) {
  43. perror("fork");
  44. _exit(1);
  45. }
  46. if (pid1 == 0){
  47. close(fd12[0]);
  48. close(fd21[1]);
  49. pingpong(fd21[0], fd12[1], 1, max_num);
  50. close(fd21[0]);
  51. close(fd12[1]);
  52. _exit(0);
  53. }
  54.  
  55. if ((pid2 = fork()) < 0) {
  56. perror("fork");
  57. _exit(1);
  58. }
  59. if (pid2 == 0){
  60. close(fd21[0]);
  61. close(fd12[1]);
  62. pingpong(fd12[0], fd21[1], 2, max_num);
  63. close(fd12[0]);
  64. close(fd21[1]);
  65. _exit(0);
  66. }
  67. int x = 1;
  68. write(fd21[1], &x, sizeof(x));
  69. close(fd12[0]);
  70. close(fd21[1]);
  71. close(fd21[0]);
  72. close(fd12[1]);
  73. wait(NULL);
  74. wait(NULL);
  75. printf("%s\n", "Done");
  76. fflush(stdout);
  77. _exit(0);
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement