pipe.c 566 B

123456789101112131415161718192021222324252627282930313233343536
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5. int main(int argc, char ** argv)
  6. {
  7. int pipes[2];
  8. pipe(pipes);
  9. int pid1 = fork();
  10. if (pid1 < 0) {
  11. printf("fork failed\n");
  12. return -1;
  13. }
  14. if (pid1 == 0) {
  15. close(pipes[0]);
  16. write(pipes[1], "hello world",12);
  17. return 0;
  18. }
  19. char buffer[20];
  20. int bytes;
  21. close(pipes[1]);
  22. bytes = read(pipes[0], buffer, 12);
  23. buffer[bytes] = 0;
  24. printf("%s\n", buffer);
  25. waitpid(pid1, NULL, 0);
  26. return 0;
  27. }