pipe.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. int main(void) {
  7. int pid, pip[2];
  8. char instring[20];
  9. char * outstring = "Hello World!";
  10. if (pipe(pip) < 0) {
  11. perror("pipe");
  12. return EXIT_FAILURE;
  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 EXIT_FAILURE;
  27. } else if (bytes != strlen(outstring)) {
  28. fprintf(stderr, "pipe write: %d != %ld\n", bytes, strlen(outstring));
  29. return EXIT_FAILURE;
  30. }
  31. return EXIT_SUCCESS;
  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 EXIT_FAILURE;
  47. } else if (bytes != strlen(outstring)) {
  48. fprintf(stderr, "pipe read: %d != %ld\n", bytes, strlen(outstring));
  49. return EXIT_FAILURE;
  50. } else if (memcmp(instring, outstring, strlen(outstring)) != 0) {
  51. fprintf(stderr, "pipe read does not match pipe write\n");
  52. return EXIT_FAILURE;
  53. } else {
  54. printf("%s\n", instring);
  55. }
  56. return EXIT_SUCCESS;
  57. }
  58. }