2
0

pipe.c 1.8 KB

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