pipe.c 717 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/wait.h>
  4. #include <unistd.h>
  5. int main(int argc, char** argv) {
  6. int pipes[2];
  7. if (pipe(pipes) < 0) {
  8. perror("pipe error");
  9. return 1;
  10. }
  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. if (write(pipes[1], "hello world", 12) != 12) {
  19. perror("write error");
  20. return 1;
  21. }
  22. return 0;
  23. }
  24. char buffer[20];
  25. int bytes;
  26. close(pipes[1]);
  27. bytes = read(pipes[0], buffer, 12);
  28. buffer[bytes] = 0;
  29. printf("%s\n", buffer);
  30. waitpid(pid1, NULL, 0);
  31. return 0;
  32. }