Advertisement
Tobiahao

S01_LAB02_04a

Nov 13th, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.26 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. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <fcntl.h>
  10. #include <unistd.h>
  11. #include <wait.h>
  12. #include <string.h>
  13.  
  14. #define SOME_MESSAGE "Wiadomosc"
  15. #define BUFFER_SIZE 128
  16.  
  17. int main(void)
  18. {
  19.     int fd[2];
  20.     char buffer[BUFFER_SIZE];
  21.     pid_t pid;
  22.  
  23.     if(pipe(fd) == -1){
  24.         perror("pipe");
  25.         return EXIT_FAILURE;
  26.     }
  27.  
  28.     printf("Flaga O_NONBLOCK nie zostala ustawiona\n\n");
  29.  
  30.     pid = fork();
  31.     if(pid == -1){
  32.         perror("fork");
  33.         return EXIT_FAILURE;
  34.     }
  35.     else if(pid == 0){
  36.         if(write(fd[1], SOME_MESSAGE, strlen(SOME_MESSAGE)) == -1){
  37.             perror("write");
  38.             return EXIT_FAILURE;
  39.         }  
  40.  
  41.         printf("Potomek: Wiadomosc wyslana [%s]!\n", SOME_MESSAGE);
  42.  
  43.         if(close(fd[1]) == -1){
  44.             perror("close");
  45.             return EXIT_FAILURE;
  46.         }
  47.     }
  48.     else{
  49.         wait(NULL);
  50.  
  51.         memset(buffer, '\0', BUFFER_SIZE);
  52.         if(read(fd[0], buffer, BUFFER_SIZE) == -1){
  53.             perror("read");
  54.             return EXIT_FAILURE;
  55.         }
  56.  
  57.         printf("Rodzic: Wiadomosc otrzymana [%s]!\n", buffer);
  58.  
  59.         if(close(fd[0]) == -1){
  60.             perror("close");
  61.             return EXIT_FAILURE;
  62.         }
  63.     }
  64.  
  65.     return EXIT_FAILURE;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement