pipe.c 2.1 KB

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