Advertisement
Haifisch7734

PIPE

Oct 15th, 2014
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 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. int main(){
  9.     char name[256];
  10.     int pipePW[2], pipeCW[2], pid;
  11.    
  12.     if (pipe(pipePW) < 0)
  13.         perror("Błąd PIPE\n");
  14.     if (pipe(pipeCW) < 0)
  15.         perror("Błąd PIPE\n");
  16.    
  17.     pid = fork();
  18.     if (pid == -1){
  19.         perror("Błąd forkowania\n");
  20.         exit(1);
  21.         }
  22.     if (pid == 0){
  23.         close(pipePW[1]);
  24.         close(pipeCW[0]);
  25.         char buff[20] = "";
  26.         char status;
  27.         FILE* file;
  28.         read(pipePW[0],&name,sizeof(name));
  29.  
  30.         if ((file = fopen(name,"r")) == NULL){
  31.             status = -1;
  32.             write(pipeCW[1],&status,1);
  33.             exit(1);
  34.             }
  35.         do {
  36.             status = fread(&buff,1,20,file);
  37.             write(pipeCW[1],&status,1);
  38.             write(pipeCW[1],&buff,status);
  39.             } while (status != 0); 
  40.         exit(0);
  41.         }
  42.     else {
  43.         close(pipePW[0]);
  44.         close(pipeCW[1]);
  45.         char buff[20] = "";
  46.         char size;
  47.        
  48.         puts("Podaj nazwę pliku do wczytania");
  49.         scanf("%s",name);      
  50.         write(pipePW[1],&name,sizeof(name));
  51.  
  52.         do {
  53.             read(pipeCW[0],&size,1);
  54.             if (size == -1){
  55.                 puts("Problem z plikiem");
  56.                 wait(NULL);
  57.                 exit(-1);
  58.             }
  59.             if (size == 0)
  60.                 break;
  61.             read(pipeCW[0],&buff,size);
  62.             printf("%s",buff);
  63.             buff[0] = '\0';        
  64.         } while(size != 0);
  65.         wait(NULL);
  66.         }
  67.    
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement