SHARE
TWEET

Untitled

a guest Oct 14th, 2019 78 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. int
  9. main() {
  10.  
  11.   pid_t c1_pid = fork();
  12.   int c1_status = 0;
  13.  
  14.   int pipefd[2];
  15.  
  16.   if (pipe(pipefd) == -1) {
  17.       perror("pipe");
  18.       exit(EXIT_FAILURE);
  19.   }
  20.  
  21.  
  22.   if (c1_pid < 0) {
  23.     perror("fork");
  24.     exit(EXIT_FAILURE);
  25.   } else if (c1_pid == 0) {
  26.     // child
  27.  
  28.     printf("first child\n");
  29.    
  30.     dup2(pipefd[1], STDOUT_FILENO);
  31.     close(pipefd[1]);
  32.     close(pipefd[0]);
  33.  
  34.     printf("hello world\n");
  35.  
  36.   } else {
  37.     // parent
  38.  
  39.     pid_t c2_pid = fork();
  40.     int c2_status = 0;
  41.  
  42.     if (c2_pid < 0) {
  43.       perror("fork");
  44.       exit(EXIT_FAILURE);
  45.     } else if (c2_pid == 0) {
  46.  
  47.       printf("second child\n");
  48.      
  49.       dup2(pipefd[0], STDIN_FILENO);
  50.       close(pipefd[1]);
  51.       close(pipefd[0]);
  52.  
  53.       char* myargs[2];
  54.       myargs[0] = strdup("/bin/cat");
  55.       myargs[1] = NULL;
  56.  
  57.       execvp(myargs[0], myargs);
  58.  
  59.     } else {
  60.       pid_t finished_c2_pid = waitpid(c2_pid, &c2_status, WUNTRACED);
  61.       printf("finished c2 process: %d\n", finished_c2_pid);
  62.     }
  63.  
  64.     pid_t finished_c1_pid = waitpid(c1_pid, &c1_status, WUNTRACED);
  65.     printf("finished c1 process: %d\n", finished_c1_pid);
  66.   }
  67.  
  68.   return 0;
  69. }
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
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top