orzechtbg

Współbieżne.LAB3. ZAD1

Oct 22nd, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.44 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7.  
  8. char buffor1[50], buffor2[50];
  9. char nazwa_pliku[50];
  10. int pipe_child[2], pipe_parent[2];
  11. int childpid, n;
  12.  
  13. int main(){
  14.     if(pipe(pipe_child) < 0)
  15.         perror("Blad pipe_child\n");
  16.     if(pipe(pipe_parent) < 0)
  17.         perror("Blad pipe_parent\n");
  18.  
  19.     if((childpid = fork()) == -1){
  20.         perror("nie moge forknac\n");
  21.     } else {
  22.         if(childpid == 0){
  23.             close(pipe_child[1]);
  24.             close(pipe_parent[0]);
  25.  
  26.             if((n = read(pipe_child[0], buffor1, sizeof(buffor1))) <= 0)
  27.                 perror("Blad odczytu\n");
  28.  
  29.             FILE *plik = fopen(buffor1, "r");
  30.  
  31.             if(plik == NULL){
  32.                 if(write(pipe_parent[1], "Blad otwarcia pliku\n", 20) != 20)
  33.                     perror("Blad zapisu\n");
  34.             } else {
  35.                 while(fgets(buffor1, sizeof(buffor1), plik) != NULL)
  36.                             write(pipe_parent[1], buffor1, sizeof(buffor1));
  37.             }
  38.  
  39.             fclose(plik);
  40.  
  41.             close(pipe_child[0]);
  42.             close(pipe_parent[1]);
  43.         } else {
  44.             close(pipe_child[0]);
  45.             close(pipe_parent[1]);
  46.  
  47.             printf("Nazwa pliku: ");       
  48.             scanf("%s", nazwa_pliku);
  49.  
  50.             if(write(pipe_child[1], nazwa_pliku, sizeof(nazwa_pliku)) != sizeof(nazwa_pliku))
  51.                 perror("Blad zapisu\n");
  52.  
  53.             while(read(pipe_parent[0], buffor2, sizeof(buffor2)) > 0)
  54.                             write(1, buffor2, strlen(buffor2));
  55.  
  56.             wait(NULL);
  57.             close(pipe_child[1]);
  58.             close(pipe_parent[0]);
  59.         }
  60.     }
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment