Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
983 views
in Technique[技术] by (71.8m points)

c - How do I perform a non-blocking fopen on a named pipe (mkfifo)?

If I have a program which creates and attempts to open a named pipe using mkfifo, how can I open a pipe for reading or writing without blocking?

Specifically, I'm writing a C program which can be run with or without a gui (written in Java).

In the C program, I successfully create the named pipes using mkfifo, however when I do

FILE* in = fopen(PIPE_IN, "r"); /* Where PIPE_IN is the filename*/

fopen doesn't return until the GUI opens that pipe for writing. What I wish to do is have that pipe ready to be read once (if) the GUI decides to write to it - I'll be putting the file descriptor in a select() call. It's reasonable to expect that the java GUI may never actually be started, so I cannot rely on it to open the other end of the pipe at any specific point or even at all.

I will also have a second pipe open for writing, and I assume I will have the same problem. Further, I can't set O_NONBLOCK on an output pipe that has no reader.

Any suggestions?

(This is running on a linux system)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could open() your pipe O_RDONLY | O_NONBLOCK, and if you want the C stream, you can get it with fdopen(). However, there might be a problem with the select() - AFAIK, a pipe fd open for reading that has no writer is always prepared for reading, and read() returns 0, so the select() would fire indefinitely.

A kludgy way of overcoming this would be to open the pipe O_RDWR; that is, have at least one writer (your C++ program). Which would solve your problem anyway.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...