3

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
  • Use strace(1) on your program. And call perror(3) on error. Commented Dec 19, 2016 at 8:00
  • 1
    "Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa." linux.die.net/man/3/mkfifo Commented Dec 19, 2016 at 8:03

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Basile, after creating a FIFO and writing somthing to it. Then I tried to read this FIFO from another process and it works (I mean, it can exit)
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.