How to see the error of open()

774 views Asked by At

I am working with pipes and one pipe won't open, even though mkfifo() was successful.

I have this:

/* create the FIFO (named pipe) */
int ret_mk = mkfifo(out_myfifo, 0666);
if(ret_mk < 0) {
  perror(out_myfifo);
  unlink(out_myfifo);
  return -1;
}

printf("ret_mk = %d\n", ret_mk);
/* write to the FIFO */
out_fd = open(out_myfifo, O_WRONLY);
printf("out_fd = %d\n", out_fd);

but nothing gets printed after open(), even a print of random text won't show up.

From here we have:

The open() function returns an integer value, which is used to refer to the file. If unsuccessful, it returns -1, and sets the global variable errno to indicate the error type.

What can I do to see why it won't open?

1

There are 1 answers

7
Basile Starynkevitch On BEST ANSWER

Read fifo(7). For FIFOs, an open call may block. To make open(2) non-blocking, use O_NONBLOCK in the flag argument:

out_fd = open(out_myfifo, O_WRONLY|O_NONBLOCK);
if (out_fd<0) perror(out_myfifo);
printf("%d\n", out_fd);

But usually you want a blocking open for write on a FIFO, because some other process should open the same FIFO for reading (and you want your writing process to wait that to happen).

Notice that there is no way to poll(2) the event that someone else has opened the other end of your FIFO (because poll wants an opened file descriptor). See also inotify(7); you could also want to use unix(7) sockets.

BTW, you could also use strace(1) for debugging purposes.

See also intro(2) and Advanced Linux Programming.