Advertisement
d1cor

ej_pipe.c

May 31st, 2017
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.13 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/wait.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <string.h>
  7.  
  8. int
  9. main(int argc, char *argv[])
  10. {
  11.    int pipefd[2];
  12.    pid_t cpid;
  13.    char buf;
  14.  
  15.    if (argc != 2) {
  16.        fprintf(stderr, "Usage: %s <string>\n", argv[0]);
  17.        exit(EXIT_FAILURE);
  18.    }
  19.  
  20.    if (pipe(pipefd) == -1) {
  21.        perror("pipe");
  22.        exit(EXIT_FAILURE);
  23.    }
  24.  
  25.    cpid = fork();
  26.    if (cpid == -1) {
  27.        perror("fork");
  28.        exit(EXIT_FAILURE);
  29.    }
  30.  
  31.    if (cpid == 0) {    /* Child reads from pipe */
  32.        close(pipefd[1]);          /* Close unused write end */
  33.  
  34.        while (read(pipefd[0], &buf, 1) > 0)
  35.            write(STDOUT_FILENO, &buf, 1);
  36.  
  37.        write(STDOUT_FILENO, "\n", 1);
  38.        close(pipefd[0]);
  39.        _exit(EXIT_SUCCESS);
  40.  
  41.    } else {            /* Parent writes argv[1] to pipe */
  42.        close(pipefd[0]);          /* Close unused read end */
  43.        write(pipefd[1], argv[1], strlen(argv[1]));
  44.        close(pipefd[1]);          /* Reader will see EOF */
  45.        wait(NULL);                /* Wait for child */
  46.        exit(EXIT_SUCCESS);
  47.    }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement