pipe.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //http://www2.cs.uregina.ca/~hamilton/courses/330/notes/unix/pipes/pipes.html
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. int main()
  6. {
  7. int pid, pip[2];
  8. char instring[20];
  9. char * outstring = "Hello World!";
  10. pipe(pip);
  11. pid = fork();
  12. if (pid == 0) /* child : sends message to parent*/
  13. {
  14. puts("Child: Close Read");
  15. /* close read end */
  16. close(pip[0]);
  17. puts("Child: Write");
  18. /* send 7 characters in the string, including end-of-string */
  19. write(pip[1], outstring, strlen(outstring));
  20. puts("Child: Close Write");
  21. /* close write end */
  22. close(pip[1]);
  23. }
  24. else /* parent : receives message from child */
  25. {
  26. puts("Parent: Close Write");
  27. /* close write end */
  28. close(pip[1]);
  29. puts("Parent: Read");
  30. /* read from the pipe */
  31. read(pip[0], instring, 7);
  32. puts("Parent: Close Read");
  33. /* close read end */
  34. close(pip[0]);
  35. }
  36. return 0;
  37. }