Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.40 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. #include <errno.h>
  6. #include <string.h>
  7. #include <sys/types.h>
  8. #include <sys/wait.h>
  9. #include <errno.h>
  10.  
  11. #define MESSAGE_SIZE 100
  12.  
  13. extern int errno;
  14.  
  15. char file_name[20];
  16.  
  17.  
  18. void parent_process(int pipefd[]){
  19.     char message[MESSAGE_SIZE];
  20.     if(close(pipefd[1]) < 0)
  21.         perror("parent - close write");
  22.     if(read(pipefd[0], message, sizeof(message)) < 0)
  23.         perror("read");
  24.    
  25.     printf("\nOdebrana wiadomosc:\t\t%s\n", message);
  26.  
  27.     if(close(pipefd[0]) < 0)
  28.         perror("parent - close read");
  29.  
  30.     wait(0);
  31. }
  32.  
  33. void child_process(int pipefd[], char file_name[]){
  34.     char message[MESSAGE_SIZE];
  35.  
  36.     if(close(pipefd[0]) < 0)   
  37.         perror("close read - child");
  38.  
  39.     int errnum;
  40.     FILE *file = fopen(file_name, "r");
  41.    
  42.     if(file == NULL){
  43.         errnum = errno;
  44.         strcpy(message, strerror(errnum));
  45.     } else {
  46.         fread(message, sizeof(char), sizeof(message), file);
  47.     }
  48.  
  49.     printf("Wiadomosc do przekazania:\t%s", message);
  50.     if(write(pipefd[1], message, strlen(message)) < 0)
  51.             perror("child - write content");
  52.        
  53.     fclose(file);
  54.    
  55.     exit(0);
  56. }
  57.  
  58.  
  59. int main(){
  60.     int pipefd[2];
  61.     if(pipe(pipefd)<0)
  62.         perror("pipe");
  63.  
  64.     printf("Podaj nazwe pliku: ");
  65.     scanf("%s", file_name);
  66.  
  67.  
  68.     int pid = fork();
  69.     if(pid == -1)
  70.         perror("fork");
  71.     if(pid == 0)
  72.         child_process(pipefd, file_name);
  73.     else
  74.         parent_process(pipefd);
  75.  
  76.  
  77.  
  78.     return 0;
  79.  
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement