pipe.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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(void) {
  6. int pid, pip[2];
  7. char instring[20];
  8. char * outstring = "Hello World!";
  9. if (pipe(pip) < 0) {
  10. perror("pipe");
  11. return 1;
  12. }
  13. pid = fork();
  14. if (pid == 0) /* child : sends message to parent*/
  15. {
  16. /* close read end */
  17. close(pip[0]);
  18. /* send 7 characters in the string, including end-of-string */
  19. int bytes = write(pip[1], outstring, strlen(outstring));
  20. /* close write end */
  21. close(pip[1]);
  22. /* check result */
  23. if (bytes < 0) {
  24. perror("pipe write");
  25. return 1;
  26. } else if (bytes != strlen(outstring)) {
  27. fprintf(stderr, "pipe write: %d != %ld\n", bytes, strlen(outstring));
  28. return 1;
  29. }
  30. return 0;
  31. }
  32. else /* parent : receives message from child */
  33. {
  34. /* close write end */
  35. close(pip[1]);
  36. /* clear memory */
  37. memset(instring, 0, sizeof(instring));
  38. /* read from the pipe */
  39. int bytes = read(pip[0], instring, sizeof(instring) - 1);
  40. /* close read end */
  41. close(pip[0]);
  42. /* check result */
  43. if (bytes < 0) {
  44. perror("pipe read");
  45. return 1;
  46. } else if (bytes != strlen(outstring)) {
  47. fprintf(stderr, "pipe read: %d != %ld\n", bytes, strlen(outstring));
  48. return 1;
  49. } else if (memcmp(instring, outstring, strlen(outstring)) != 0) {
  50. fprintf(stderr, "pipe read does not match pipe write\n");
  51. return 1;
  52. } else {
  53. printf("%s\n", instring);
  54. }
  55. return 0;
  56. }
  57. return 0;
  58. }