Чтение именованного канала во время записи в него нескольких процессов - PullRequest
0 голосов
/ 16 апреля 2019

Какой способ является правильным для решения этой проблемы?

Например, у меня есть программа с именем write.c, которая имеет 4 дочерних процесса, а дочерние процессы записывают свои PID в один глобальный именованный канал.

Другая программа с именем read.c должна прочитать этот PID.

У меня есть подход, подобный приведенному ниже, но у этого подхода есть некоторые проблемы. Он не может прочитать все PID, иногда 3 из них, а иногда и 2 из них. Я думаю, что есть проблема синхронизации, как я могу решить эту проблему? :

writer.c:

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <fcntl.h> 
#include <sys/stat.h> 
#include <sys/types.h> 
#include <sys/wait.h> 
#include <unistd.h> 

int main(){ 
    int fd; 
    char * myfifo = "/tmp/myfifo"; //FIFO file
    char buffer[50]; 

    mkfifo(myfifo, 0666); //creating the FIFO

    for(int i=0;i<4;i++){ //creating 4 child process
        if(fork() == 0) { 
            fd = open(myfifo, O_WRONLY); //each child process opens the FIFO for writing their own PID.

            sprintf(buffer, "%d", getpid()); //each child process gets pid and assign it to buffer
            printf("write:%s\n", buffer);  // each child process prints to see the buffer clearly

            write(fd, buffer, strlen(buffer)+1); //each child process writes the buffer to the FIFO
            close(fd);

            exit(0); 
        } 
    } 
    for(int i=0;i<4;i++) { //waiting the termination of all 4 child processes.
        wait(NULL); 
    }
    //parent area
} 

reader.c

#include <stdio.h> 
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h> 
#include <time.h>
#include <string.h>
#include <fcntl.h> 

int main(int argc, char **argv) { 

    int fd1; 

    // FIFO file path 
    char * myfifo = "/tmp/myfifo"; 

    // Creating the named file(FIFO) 
    mkfifo(myfifo, 0666); 

    char str1[80]; //str2[80]; 
    while (1) 
    { 
        // First open in read only and read 
        fd1 = open(myfifo,O_RDONLY); 
        read(fd1, str1, 80); 

        // Print the read string and close 
        printf("read: %s\n", str1); 
        close(fd1); 
    } 
} 

1 Ответ

2 голосов
/ 16 апреля 2019

Эта строка записывает нулевой байт в fifo:

write(fd, buffer, strlen(buffer)+1);

В результате, если у вас в трубе два пида, вы прочитаете следующую строку:

1234\02345\0

И printf будет печататься только до первого \0:

1234

Чтобы исправить это, легче передать PID в двоичном формате, чем форматировать и анализировать текст:

Writer:

    if(fork() == 0) { 
        fd = open(myfifo, O_WRONLY);
        pid_t pid = getpid();
        write(fd, &pid, sizeof(pid));
        close(fd);
        exit(0); 
    } 

Читатель:

fd1 = open(myfifo,O_RDONLY); 
pid_t pid;
while (1) // whatever is your termination condition
{ 
    read(fd1, &pid, sizeof(pid)); 
    printf("read: %d\n", pid); 
} 
close(fd1); 
...