pipe.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //http://www2.cs.uregina.ca/~hamilton/courses/330/notes/unix/pipes/pipes.html
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #include "test_helpers.h"
  7. int main(void) {
  8. int pid, pip[2];
  9. char instring[20];
  10. char * outstring = "Hello World!";
  11. if (pipe(pip) < 0) {
  12. perror("pipe");
  13. exit(EXIT_FAILURE);
  14. }
  15. pid = fork();
  16. if (pid == 0) /* child : sends message to parent*/
  17. {
  18. /* close read end */
  19. close(pip[0]);
  20. /* send 7 characters in the string, including end-of-string */
  21. int bytes = write(pip[1], outstring, strlen(outstring));
  22. /* close write end */
  23. close(pip[1]);
  24. /* check result */
  25. if (bytes < 0) {
  26. perror("pipe write");
  27. exit(EXIT_FAILURE);
  28. } else if (bytes != strlen(outstring)) {
  29. fprintf(stderr, "pipe write: %d != %ld\n", bytes, strlen(outstring));
  30. exit(EXIT_FAILURE);
  31. }
  32. exit(EXIT_SUCCESS);
  33. }
  34. else /* parent : receives message from child */
  35. {
  36. /* close write end */
  37. close(pip[1]);
  38. /* clear memory */
  39. memset(instring, 0, sizeof(instring));
  40. /* read from the pipe */
  41. int bytes = read(pip[0], instring, sizeof(instring) - 1);
  42. /* close read end */
  43. close(pip[0]);
  44. /* check result */
  45. if (bytes < 0) {
  46. perror("pipe read");
  47. exit(EXIT_FAILURE);
  48. } else if (bytes != strlen(outstring)) {
  49. fprintf(stderr, "pipe read: %d != %ld\n", bytes, strlen(outstring));
  50. exit(EXIT_FAILURE);
  51. } else if (memcmp(instring, outstring, strlen(outstring)) != 0) {
  52. fprintf(stderr, "pipe read does not match pipe write\n");
  53. exit(EXIT_FAILURE);
  54. } else {
  55. printf("%s\n", instring);
  56. }
  57. exit(EXIT_SUCCESS);
  58. }
  59. }