Program with mkfifo() and open() cannot exit

1.3k Views Asked by At

I am trying to use FIFO for interprocessing. But when trying to create a FIFO and then open it, my program hangs (cannot exit).

if (mkfifo("./fifo.txt", S_IRUSR | S_IWUSE) < 0) {
    fprint("Can not create fifo");
    return 1;
}
if ((readfd = open("./fifo.txt", O_RDONLY)) < 0) {
    return 1;
}

What am I doing wrong here?

Thank you very much.

2

There are 2 best solutions below

1
On

Read fifo(7), notably:

Normally, opening the FIFO blocks until the other end is opened also.

So I guess that your call to open(2) is blocked. Perhaps you want to pass the O_NONBLOCK flag.

You should use strace(1) to debug your program (and perhaps also strace the other program on the other end of the fifo). And call perror(3) on error.

Perhaps using unix(7) sockets could be more relevant in your case. You can then poll(2) before accept(2)

You should read Advanced Linux Programming.

0
On

Here is an example code:

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

void child(void)
{
    int fd = 0;
    if ((fd = open("./fifo.txt", O_WRONLY)) < 0) {
        return;
    }

    write(fd, "hello world!", 12);
}

void parent(void)
{
    int fd = 0;
    if ((fd = open("./fifo.txt", O_RDONLY)) < 0) {
        return;
    }

    char buf[36] = {0};
    read(fd, buf, 36);
    printf("%s\n", buf);
}


int main(void)
{
    pid_t pid = 0;

    if (mkfifo("./fifo.txt", S_IRUSR | S_IWUSR) < 0) {
        printf("Can not create fifo\n");
        return 1;
    }

    pid = fork();
    if (pid == 0) {
        printf("child process\n");
        child();
    } else if (pid < 0) {
        printf("fork error\n");
        return -1;
    }

    parent();
}