pipe.c 812 B

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