pipe.c 574 B

1234567891011121314151617181920212223242526272829303132333435
  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. pipe(pipes);
  8. int pid1 = fork();
  9. if (pid1 < 0) {
  10. printf("fork failed\n");
  11. return -1;
  12. }
  13. if (pid1 == 0) {
  14. close(pipes[0]);
  15. write(pipes[1], "hello world", 12);
  16. return 0;
  17. }
  18. char buffer[20];
  19. int bytes;
  20. close(pipes[1]);
  21. bytes = read(pipes[0], buffer, 12);
  22. buffer[bytes] = 0;
  23. printf("%s\n", buffer);
  24. waitpid(pid1, NULL, 0);
  25. return 0;
  26. }