SHARE
TWEET

Untitled

a guest Oct 14th, 2019 96 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <sys/types.h>
  2. #include <sys/wait.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7.  
  8. #define READ_END 0
  9. #define WRITE_END 1
  10.  
  11.  
  12. int
  13. main() {
  14.  
  15.   pid_t c1_pid = fork();
  16.   int c1_status = 0;
  17.  
  18.   int pipefd[2];
  19.  
  20.   if (pipe(pipefd) == -1) {
  21.       perror("pipe");
  22.       exit(EXIT_FAILURE);
  23.   }
  24.  
  25.  
  26.   if (c1_pid < 0) {
  27.     perror("fork");
  28.     exit(EXIT_FAILURE);
  29.   } else if (c1_pid == 0) {
  30.     // child 1
  31.  
  32.     printf("first child\n");
  33.    
  34.     dup2(pipefd[WRITE_END], STDOUT_FILENO);
  35.     close(pipefd[WRITE_END]);
  36.     close(pipefd[READ_END]);
  37.  
  38.     printf("hello world\n");
  39.  
  40.   } else {
  41.     // parent
  42.  
  43.     pid_t c2_pid = fork();
  44.     int c2_status = 0;
  45.  
  46.     if (c2_pid < 0) {
  47.       perror("fork");
  48.       exit(EXIT_FAILURE);
  49.     } else if (c2_pid == 0) {
  50.       // child 2
  51.  
  52.       printf("second child\n");
  53.      
  54.       dup2(pipefd[READ_END], STDIN_FILENO);
  55.       close(pipefd[WRITE_END]);
  56.       close(pipefd[READ_END]);
  57.  
  58.       char* myargs[2];
  59.       myargs[0] = strdup("/bin/cat");
  60.       myargs[1] = NULL;
  61.  
  62.       execvp(myargs[0], myargs);
  63.  
  64.     } else {
  65.       // parent
  66.  
  67.       pid_t finished_c2_pid = waitpid(c2_pid, &c2_status, WUNTRACED);
  68.       printf("finished c2 process: %d\n", finished_c2_pid);
  69.     }
  70.  
  71.     close(pipefd[WRITE_END]);
  72.     close(pipefd[READ_END]);
  73.  
  74.     pid_t finished_c1_pid = waitpid(c1_pid, &c1_status, WUNTRACED);
  75.     printf("finished c1 process: %d\n", finished_c1_pid);
  76.   }
  77.  
  78.   return 0;
  79. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top