0

I have a named pipe in my C++ program. A childprocess writes a value in it and the parent process reads it. I created the pipe by mkfifo and all operations are blocking (fifo cannot be opened for reading before it is tried to open for writing and v.v. unfortunately sometimes my childprocess does not stop because of an error in a program the childprocess runs. It is not my task to fix this error in this external program but I want to make sure that the parent process does not stop for infinite time on the blocked open fifo call, but goes on after some time (without reading the value in the pipe).

So what I need it somethings like the WaitNamedPipe function. This function waits until either a time-out interval elapses or an instance of the specified named pipe is available for connection. http://ist.marshall.edu/ist480acp/namedpipes.html#WaitNamedPipe

Another way to realize this of course also works. I tried it with a loop in the parent process in which it always tries to open the pipe for reading and then sleeps if open is not possible. That seems to have no effect, probably because the parent process is blocking on the first open call.

Thanks for any help.

Lin
  • 1

2 Answers2

3

You want O_NONBLOCK in your open(2) flags, see fifo(7). Then use select(2) or poll(2) to wait for input (with a timeout).

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
2

You can use a non-blocking pipe and select() call with a timeout. Or you can use a blocking read() call having called alarm() before it.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • What implication does a non-blocking pipe have? In general, the blocking is good I think, just in the case (which is not often) that the child process does not finish, it should not block too long. – Lin Jul 29 '11 at 15:19
  • Scroll down to PIPE_BUF on http://www.kernel.org/doc/man-pages/online/pages/man7/pipe.7.html – Maxim Egorushkin Jul 29 '11 at 15:29
  • `alarm` + `read` is a bad idea because it has an unavoidable race condition: The alarm might go off before the `read` has a chance to start. (Linux is not a real-time operating system, so in there is no guaranteed bound on the length of time between the call to `alarm` and the call to `read`.) `select` (or `poll`) with a timeout works fine and is the correct answer. – Nemo Jul 29 '11 at 15:37
  • It might. The value of using `alarm()` is that it is an easy code change. – Maxim Egorushkin Jul 29 '11 at 15:40