Facebook
From Cobalt Duck, 6 Years ago, written in C++.
Embed
Download Paste or View Raw
Hits: 296
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <sys/stat.h>
  5. #include <errno.h>
  6. #include <stdlib.h>
  7. #include <fcntl.h>
  8. #define db 0
  9.  
  10. void debug(int desc, char * tekst, char * pid)  {
  11.     char *MSG= (char *) malloc((2 + strlen(pid) + strlen(tekst)));
  12.     strcpy(MSG, pid);
  13.     strcat(MSG, "\n");
  14.     strcat(MSG, tekst);
  15.     write(desc, MSG, (int)strlen(MSG));
  16. }
  17.  
  18. int main(int argc, char *argv[]) {
  19.     pid_t parent = getppid();
  20.     char parent_str[20];
  21.     sprintf(parent_str, "%d", parent);
  22.  
  23.     pid_t pid = getpid();
  24.     char pid_str[20];
  25.     sprintf(pid_str, "%d", pid);
  26.  
  27.     int inst;
  28.     if(db == 1) inst = open("test.txt", O_CREAT | O_WRONLY | O_APPEND , S_IRUSR | S_IWUSR);
  29.  
  30.     int fd;
  31.  
  32.     if((mkfifo(parent_str, S_IRWXU | S_IRWXG | S_IRWXO)) != 0) {
  33.         if(errno == EEXIST) {
  34.             if(db == 1) debug(inst, "  READER. Fifo DUZE juz stworzone. Otwieram do odczytu.\n", pid_str);
  35.             if((fd = open(parent_str, O_RDONLY)) == -1) exit(1);
  36.         } else {
  37.             exit(1);
  38.         }
  39.     } else {
  40.         if(db == 1) debug(inst, "  READER. Fifo DUZE nie stworzone. Tworzę i otwieram do odczytu.\n", pid_str);
  41.         if((fd = open(parent_str, O_RDONLY)) == -1) exit(1);
  42.     }
  43.  
  44.     char buf[20];
  45.  
  46.     if(db == 1) debug(inst, "  READER. Za chwile zaczne czytanie z fifo.\n",  pid_str);
  47.  
  48.     while (read(fd, &buf, 20) > 0) {
  49.         int p = 0;
  50.         while(buf[p] != ' ') p++;
  51.         buf[p] = '\n';
  52.         write(1, buf, p + 1);
  53.     }
  54.  
  55.     if(db == 1) debug(inst, "  READER. Skonczylem czytac z duzego fifo bo dostalem eof.\n",  pid_str);
  56.     if(db == 1) close(inst);
  57.  
  58.     close(fd);
  59.  
  60.     return 0;
  61. }
  62.