C   77
childin
Guest on 1st June 2022 01:27:08 AM


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5.  
  6. #define BUFSIZE 8192
  7. char buf[BUFSIZE];
  8.  
  9. int ifd[2] = {0, 0};    /* ifd[0] is read, ifd[1] is write */
  10.  
  11. int
  12. main(int argc, char *argv[])
  13. {
  14.   int status;
  15.   int rc;
  16.  
  17.   pipe(ifd);
  18.  
  19.   rc = fork();
  20.   if (rc < 0) {
  21.     perror("fork failed: ");
  22.     exit(1);
  23.   } else if (rc == 0) {
  24.     close(0);
  25.     close(ifd[1]);
  26.     dup2(ifd[0],0);
  27.     argv++;
  28.     execve(argv[0], argv, 0);
  29.   } else {
  30.     size_t count = 5;
  31.     close(ifd[0]);
  32.     count = read(0, buf, count);
  33.     if (count == -1)  {
  34.       perror("parent read from stdin failed");
  35.       exit(1);
  36.     }
  37.     count = write(ifd[1], buf, count);
  38.     if (count == -1) {
  39.       perror("parent write to child failed");
  40.       exit(1);
  41.     }
  42.     waitpid(rc, &status, 0);
  43.     printf("child %d exited with status %d\n", rc,
  44.            WEXITSTATUS(status));
  45.   }
  46. }

Raw Paste

Login or Register to edit or fork this paste. It's free.