Tobiahao

S01_LAB02_04b

Nov 13th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. /*
  2. Napisz program, który stworzy potok i wykorzysta go do komunikacji mi ę dzy
  3. dwoma spokrewnionymi procesami. Zadanie wykonaj dla dwóch przypadków:
  4. z ustawion ą flag ą O_NONBLOCK i bez.
  5. */
  6.  
  7. #define _GNU_SOURCE
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <fcntl.h>
  11. #include <unistd.h>
  12. #include <wait.h>
  13. #include <string.h>
  14.  
  15. #define SOME_MESSAGE "Wiadomosc"
  16. #define BUFFER_SIZE 128
  17.  
  18. int main(void)
  19. {
  20.     int fd[2];
  21.     char buffer[BUFFER_SIZE];
  22.     pid_t pid;
  23.  
  24.     if(pipe2(fd, O_NONBLOCK) == -1){
  25.         perror("pipe");
  26.         return EXIT_FAILURE;
  27.     }
  28.  
  29.     printf("Flaga O_NONBLOCK ustawiona\n\n");
  30.  
  31.     pid = fork();
  32.     if(pid == -1){
  33.         perror("fork");
  34.         return EXIT_FAILURE;
  35.     }
  36.     else if(pid == 0){
  37.         if(write(fd[1], SOME_MESSAGE, strlen(SOME_MESSAGE)) == -1){
  38.             perror("write");
  39.             return EXIT_FAILURE;
  40.         }  
  41.  
  42.         printf("Potomek: Wiadomosc wyslana [%s]!\n", SOME_MESSAGE);
  43.  
  44.         if(close(fd[1]) == -1){
  45.             perror("close");
  46.             return EXIT_FAILURE;
  47.         }
  48.     }
  49.     else{
  50.         wait(NULL);
  51.  
  52.         memset(buffer, '\0', BUFFER_SIZE);
  53.         if(read(fd[0], buffer, BUFFER_SIZE) == -1){
  54.             perror("read");
  55.             return EXIT_FAILURE;
  56.         }
  57.  
  58.         printf("Rodzic: Wiadomosc otrzymana [%s]!\n", buffer);
  59.  
  60.         if(close(fd[0]) == -1){
  61.             perror("close");
  62.             return EXIT_FAILURE;
  63.         }
  64.     }
  65.  
  66.     return EXIT_FAILURE;
  67. }
Add Comment
Please, Sign In to add comment