pipe.c 742 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <sys/wait.h>
  7. int main(int argc, char ** argv)
  8. {
  9. int pipes[2];
  10. pipe(pipes);
  11. int pid1 = fork();
  12. if (pid1 < 0) {
  13. printf("fork failed\n");
  14. return -1;
  15. }
  16. if (pid1 == 0) {
  17. close(pipes[0]);
  18. write(pipes[1], "hello world",12);
  19. return 0;
  20. }
  21. char buffer[20];
  22. int bytes;
  23. close(pipes[1]);
  24. bytes = read(pipes[0], buffer, 12);
  25. buffer[bytes] = 0;
  26. printf("%s\n", buffer);
  27. waitpid(pid1, NULL, 0);
  28. return 0;
  29. }