Advertisement
Guest User

Untitled

a guest
Nov 26th, 2014
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5. #include <string.h>
  6.  
  7. int main(void)
  8. {
  9.     int pid,
  10.         c_fd[2],
  11.         p_fd[2];
  12.        
  13.     char *str;
  14.  
  15.     if (pipe(c_fd) == -1 || pipe(p_fd) == -1)
  16.     {
  17.         fprintf(stderr, "Pipe failed.\n");
  18.         exit(1);
  19.     }
  20.  
  21.     pid = fork();
  22.     if (pid == -1)
  23.     {
  24.         fprintf(stderr, "Fork failed.\n");
  25.         exit(1);
  26.     }
  27.     // child process
  28.     else if (pid == 0)
  29.     {
  30.         // redirect stdin to c_fd output and close c_fd input
  31.         dup2(0, c_fd[0]);
  32.         close(c_fd[1]);
  33.        
  34.         // redirect stdout to p_fd input and close p_fd output
  35.         dup2(1, p_fd[1]);
  36.         close(p_fd[0]);
  37.        
  38.         while (read(c_fd[0], &str, 11) != 0)
  39.             if (strcmp(str, "Guten Tag!\n") == 0)
  40.                 printf("Oh, hallo!\n");
  41.        
  42.         exit(0);
  43.     }
  44.     // parent process
  45.     else
  46.     {
  47.         // redirect stdout to c_fd input and close c_fd output
  48.         dup2(1, c_fd[1]);
  49.         close(c_fd[0]);
  50.        
  51.         // redirect stdin to p_fd output and close p_fd input
  52.         dup2(0, p_fd[0]);
  53.         close(p_fd[1]);
  54.        
  55.         printf("Guten Tag!\n");
  56.        
  57.         wait(&pid);
  58.        
  59.         printf("Kindprozess hat erfolgreich geantwortet!\n");
  60.     }
  61.    
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement