0

I have two problems with my code.

First problem is that once I create a fifo, I don't know how to add a condition in the code so in future running, if the fifo exists - then just don't create it. Tried to google, "access" didn't work (it just stucked on there and didn't continue).

My second problem is, that the code is stuck in the "open("MyFifo..." line, even if it's the first time after I created the fifo (meaning I just created the fifo, mkfifo succeed, and I reach open() line - it's stuck there).

//create new fifo if(mkfifo("myFifo",0666)<0) { perror("fifo creation failed."); exit(1); } //get fifo fd if((fd=open("myFifo",O_RDONLY))==-1) { perror("failed opening fifo."); exit(1); } 

Any ideas what am I doing wrong?

2 Answers 2

1

The function call you’re looking for is stat. If the file exists, it will fill a struct stat with file attributes such as modification time. If the file does not exist, stat() will return -1 and errno will be set to EACCESS.


The mkfifo man page says,

Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa.

To get open() to stop hanging, start another process that writes to the FIFO first. If the other process opens the FIFO for writing first, the reading program won’t hang at all on open().

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

4 Comments

Thanks. Another question: reading from a fifo is blocking either? I mean, if I read an empty fifo, my process will be blocked until someone writes to it? How can I implement "read from fifo when someone has written to it"?
read on a FIFO blocks until another process writes to it. See Beej’s Guide to Unix IPC.
EACCESS is not the only possible error you'll get from stat(); you could get ENOTDIR if the name is a pathname and one of the components is a non-existent directory, or ELOOP, or ... It is not necessarily infeasible to simply try creating the FIFO, and only complain if the error is not EEXIST. Then you know the name exists; you simply need to use stat() to validate whether it is a FIFO after all (S_ISFIFO()).
This suffers from a TOCTOU window. Checking the error code from mkfifo() is better.
1

The following will try to create the FIFO file. If it exists, it will just continue and not error out. No need to call stat.

if(mkfifo(FIFO_FILE, 0777) == -1 && errno != EEXIST) { <HANDLE ERROR> } 

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.