Tobiahao

S01_Program_01

Nov 14th, 2017
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.26 KB | None | 0 0
  1. /*
  2. Napisac program, który stworzy 2 procesy: macierzysty i potomny. Przez proces rodzicielski 10 raz wyslać wiadomosć (np. Hello world) do potomnego co 3 sekundy( sleep() ) Dla komunikacji należy użyc lącza nienazwanego (pipe)
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <string.h>
  9.  
  10. #define WIADOMOSC "Hello world"
  11. #define ROZMIAR 128
  12.  
  13. int main(void)
  14. {
  15.     pid_t pid;
  16.     int pipefd[2];
  17.     char buffer[ROZMIAR];
  18.  
  19.     if(pipe(pipefd) == -1){
  20.         perror("pipe");
  21.         return EXIT_FAILURE;
  22.     }
  23.  
  24.     pid = fork();
  25.     if(pid == -1){
  26.         perror("fork");
  27.         return EXIT_FAILURE;
  28.     }
  29.     else if(pid == 0){
  30.         for(int i = 0; i < 10; i++){
  31.             memset(buffer, '\0', ROZMIAR);
  32.             if(read(pipefd[0], buffer, ROZMIAR) == -1){
  33.                 perror("read");
  34.                 return EXIT_FAILURE;
  35.             }
  36.             printf("Wiadomosc: %s\n", buffer);
  37.         }  
  38.  
  39.         if((close((pipefd[0]) == -1)) || (close(pipefd[1]) == -1)){
  40.             perror("close");
  41.             return EXIT_FAILURE;
  42.         }
  43.     }
  44.     else{
  45.         for(int i = 0; i < 10; i++){
  46.             if(write(pipefd[1], WIADOMOSC, strlen(WIADOMOSC)) == -1){
  47.                 perror("write");
  48.                 return EXIT_FAILURE;
  49.             }  
  50.             sleep(3);
  51.         }
  52.  
  53.         if((close(pipefd[1]) == -1) || (close(pipefd[0]) == -1)){
  54.             perror("close");
  55.             return EXIT_FAILURE;
  56.         }
  57.     }
  58.  
  59.     return EXIT_SUCCESS;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment