Advertisement
Guest User

ping pong

a guest
May 25th, 2020
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.77 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4.  
  5. void child(int p[2]) {
  6.     int value[1] = {0};
  7.     while (*value < 9) {
  8.         read(p[0], value, sizeof (int));
  9.         printf(" < < < %d\n", *value);
  10.         *value += 1;
  11.         write(p[1], value, sizeof (int));
  12.         sleep(1);
  13.     }
  14.     close(p[1]);
  15.     close(p[0]);
  16.     exit(EXIT_SUCCESS);
  17. }
  18.  
  19. int main(void) {
  20.     int pp[2];
  21.     pipe(pp);
  22.     if (fork() == 0) { child(pp); } // child() exits
  23.     int value[1] = {0};
  24.     while (*value < 9) {
  25.         printf("%d > > > ", *value);
  26.         fflush(stdout);
  27.         *value += 1;
  28.         write(pp[1], value, sizeof (int));
  29.         sleep(1);
  30.         read(pp[0], value, sizeof (int));
  31.     }
  32.     close(pp[0]);
  33.     close(pp[1]);
  34.     return 0;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement