user4612022
user4612022

Reputation:

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");
}   

Upvotes: 3

Views: 1379

Answers (1)

Ctx
Ctx

Reputation: 18420

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)

Upvotes: 6

Related Questions