简体   繁体   中英

C read from named pipe doesn't end

In child, I write to fifo "sample" and read it in parent. In the code below, parent writes terminal "sample" and wait, it doesn't exit from read function.

pid_t p;
int fd;
char str[]="sample";
char ch;

mkfifo("myfifo", FIFO_PERMS);
fd = open("myfifo", O_RDWR);
p=fork();

if(!p){

    printf("write %d byte\n", write(fd, str, 6));
}
else{

    wait(NULL);
    while(read(fd, &ch, 1)>0)

        write(STDOUT_FILENO, &ch, 1);

    close(fd);

    unlink("myfifo");
}   

This is the case, because the filedescriptor is still opened for writing, since you opened it with O_RDWR and share it with both processes. You will have to make sure, that the file descriptor is opened only for reading in the reading process, for example like this:

pid_t p;
char str[]="sample";
char ch;

mkfifo("myfifo", FIFO_PERMS);
p=fork();

if(!p){
    int fd = open("myfifo", O_WRONLY);

    printf("write %d byte\n", write(fd, str, 6));
}
else{
    int fd = open("myfifo", O_RDONLY);

    wait(NULL);
    while(read(fd, &ch, 1)>0)

        write(STDOUT_FILENO, &ch, 1);

    close(fd);

    unlink("myfifo");
}

Reason: The read() on a pipe only returns EOF when the last filedescriptor opened for writing is closed, which is never the case, when the filedescriptor from which you read is also opened for writing ( O_RDWR )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM