Dlaczego tylko jeden proces z potoku otrzymuje dane od rodzica?

0

Proces macierzysty ma przekazać procesom potomnym za pomocą łączy nazwanych dane z pliku źródłowego

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
  
int main(int argc, char **argv)
{
    int id;
    if(argc != 2)
    {
    printf("Error: Too many parameters\n");
    exit(1);
    }
  
    if(fork() != 0)
    {
        FILE *oldfile;
        oldfile = fopen(argv[1], "r");
        if(oldfile == NULL)
        {
        perror("");
        exit(1);
        }
  
        mkfifo("fifo", 0666);
        id = open("fifo", O_WRONLY);
  
        char napis[256];
        sleep(1);
        while(fgets (napis, 256, oldfile))
                {
                    write(id, napis, 256);
                }
              
        close(id);
    fclose(oldfile);
        exit(0);
    }
 
    int x;
    if((x=fork())==0)
    {
        FILE *newfile;
        newfile = fopen("K1", "w");
  
        if(newfile == NULL)
        {
        printf("Error: Couldn't create a new file\n");
        exit(1);
        }
  
        char word[256];
        char bufor[256];
        int i=1;
        id = open("fifo", O_RDONLY);
        while(read(id, word, sizeof(word))>0)
          {  sprintf(bufor,"%d ",i++);           
            fputs(bufor,newfile);
            fprintf(newfile, "%s", word);}
    close(id);
    fclose(newfile);
    exit(0);
}
  int y;
    if((y=fork())==0)
    {
        FILE *newfile1;
        newfile1 = fopen("K2", "w");
  
        if(newfile1 == NULL)
        {
        printf("Error: Couldn't create a new file\n");
        exit(1);
        }
  
        char word[256];
        char bufor[256];
        int i=1;
        id = open("fifo", O_RDONLY);
        while(read(id, word, sizeof(word))>0)
          {  
            fprintf(newfile1, "%s", word);}
    close(id);
    fclose(newfile1);
    exit(0);
}
  
    return 0;
}

Po uruchomieniu programu dzieje się tak, że tylko jeden proces otrzymuje dane od rodzica. Wiem, że może być to związane z łączem nazwanym, bo tylko raz można odczytać z łącza. Co musiałbym poprawić w kodzie, aby w obu plikach znajdowały się dane z pliku źródłowego?

0

man fifo

The FIFO must be opened on both ends (reading and writing) before data can be passed. Normally, opening the FIFO blocks until the other end is opened also.
A process can open a FIFO in nonblocking mode. In this case, opening for read-only succeeds even if no one has opened on the write side yet and opening for write-only fails with ENXIO (no such device or address) unless the other end has already been opened.

1 użytkowników online, w tym zalogowanych: 0, gości: 1