Advertisement
Guest User

4_12.c

a guest
Apr 24th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.56 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <signal.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6.  
  7. int file_pipes[2];
  8. int buffer[1];
  9. pid_t fork_result;
  10. int N = 20;
  11.  
  12. // Обработчик для родительского процесса, который прочитает, а потом запишет.
  13. void parent_rw(int nsig)
  14. {
  15.     read(file_pipes[0], buffer, sizeof(buffer));
  16.     printf("Parent has read: %s\n", buffer[0]);
  17.  
  18.     if (buffer[0] >= N)
  19.         exit(EXIT_SUCCESS);
  20.     buffer[0] += 1;
  21.     write(file_pipes[1], buffer, sizeof(buffer));
  22.     printf("Parent has sent data\n");
  23.  
  24.     kill(fork_result, SIGUSR1);
  25. }
  26.  
  27.  
  28. void child_write(int nsig)
  29. {
  30.  
  31.     read(file_pipes[0], buffer, sizeof(buffer));
  32.     printf("Child has read: %s\n", buffer[0]);
  33.     if (buffer[0] >= N)
  34.         exit(EXIT_SUCCESS);
  35.     buffer[0] += 1;
  36.     write(file_pipes[1], buffer, sizeof(buffer));
  37.     printf("Child has sent data\n");
  38.  
  39.     kill(getppid(), SIGUSR1);
  40. }
  41.  
  42.  
  43. int main()
  44. {
  45.     (void)signal(SIGUSR2, child_write);
  46.     memset(buffer, '0', sizeof(buffer));
  47.     if (pipe(file_pipes) == 0)  
  48.     {
  49.         fork_result = fork();
  50.         if (fork_result == -1)
  51.         {
  52.             fprintf(stderr, "Fork failure");
  53.             exit(EXIT_FAILURE);
  54.         }  
  55.         if (fork_result == 0)  // child.
  56.             while(1);
  57.        
  58.         else    
  59.         {   // parent
  60.             (void)signal(SIGUSR1, parent_rw);
  61.  
  62.             buffer[0] = 1;
  63.             write(file_pipes[1], buffer, sizeof(buffer));
  64.             printf("Parent has sent data\n");
  65.  
  66.             kill(fork_result, SIGUSR2);
  67.  
  68.             while(1);
  69.         }
  70.     }
  71.     exit(EXIT_SUCCESS);
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement