vakho

16.10.13 - ოპერაციული სისტემები

Oct 16th, 2013
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.87 KB | None | 0 0
  1. #include <stdio.h> // printf(), perror()
  2. #include <stdlib.h> // exit()
  3. #include <unistd.h> // EXIT_SUCCESS and EXIT_FAILURE
  4. #include <sys/stat.h> // mknod()
  5. #include <sys/wait.h> // wait()
  6. #include <sys/types.h> // read(), write(), close()
  7. #include <fcntl.h> // open()
  8.  
  9. int main()
  10. {
  11.   int fd; // file descriptor
  12.   int pr; // process
  13.   int st; // status [for wait()]
  14.   int FIFO; // for FIFO file
  15.   size_t s1, s2; // sizes for the arrays
  16.  
  17.   char str[] = "Hello world!"; // text to be written
  18.   s2 = sizeof(str);
  19.   char re_str[s2];
  20.  
  21.   char name[] = "abc.fifo"; // full file name (path)
  22.   (void) umask(0);
  23.   FIFO = mknod(name, S_IFIFO | 0644, 0); /* FIFO file */
  24.  
  25.   if (FIFO < 0)
  26.   {
  27.     perror("Unable to create FIFO!\n");
  28.     exit(EXIT_FAILURE);
  29.   }
  30.  
  31.   pr = fork(); // Creating two and exact process from this point ->
  32.   if (pr < 0)
  33.   {
  34.     perror("Process hasn\'t been created!\n");
  35.     exit(EXIT_FAILURE);
  36.   }
  37.   else // If the process has been created then ->
  38.   {
  39.     if (pr == 0) // CHILD
  40.     {
  41.       printf("[CHILD]\n");
  42.       fd = open(name, O_WRONLY); // write only
  43.       if (fd < 0)
  44.       {
  45.     perror("Can\'t open FIFO!\n");
  46.     exit(EXIT_FAILURE);
  47.       }
  48.      
  49.       s1 = write(fd, str, s2);
  50.       if (s1 != s2)
  51.       {
  52.     printf("Information hasn\'t been written properly!\n");
  53.     exit(EXIT_FAILURE);
  54.       }
  55.       close(fd);
  56.       printf("[CHILD END]\n");
  57.     }
  58.     else // PARENT
  59.     {
  60.       printf("[PARENT]\n");
  61.       wait(&st);
  62.      
  63.       fd = open(name, O_RDONLY);
  64.       if (fd < 0)
  65.       {
  66.     perror("Can\'t open FIFO!\n");
  67.     exit(EXIT_FAILURE);
  68.       }
  69.      
  70.       s1 = read(fd, re_str, s2);
  71.       if (s1 != s2)
  72.       {
  73.     printf("Information hasn\'t been read properly!\n");
  74.     exit(EXIT_FAILURE);
  75.       }
  76.       close(fd);
  77.       printf("[PARENT END]\n");
  78.     }
  79.     printf("\n%s\n", re_str);
  80.   }
  81.   exit(EXIT_SUCCESS);
  82. }
Advertisement
Add Comment
Please, Sign In to add comment