Frage

There is something I am wanting to know if there is a way to do on Unix and Unixlike systems (such as BSD, GNU/Linux, etcetera). I do not care whether I would have to use the Standard C I/O or low-level Unix I/O interface, because at this point, I am not far enough along to be committed to using one or the other for this purpose. In short, if one interface allows me to do this and the other one doesn't, it's the one that allows this that I will go with.

Anyway -- here's what I want to do. I have an input file-stream (once again, don't care if it's an ANSI "FILE" structure or a Unix file-descriptor) and I want to check to see if there is any data at this stream waiting to be read --- but here's the catch ---- if there is no data waiting to be read, yet there is the possibility of more such data coming in later on (like if at the other end of this file-stream is another program I am intereacting with) I just want my program to be able to know that there's no data yet available, so it can continue doing other operations and check back later to see if any new data has come in (as opposed to just freezing my program while it waits for more info).

Also, if there is no data waiting to be read ---- I want to know if there's any chance more might come in later (that being if on the other end of the file-stream is another program which may send further data to the stream) --- or if there is no chance of any more data coming in (that being if the program at the other end of the file-stream has terminated or closed the file-stream on it's end --- or if the file-stream references an actual file).

So, is there any way to do this in C on Unix-type systems? If so, how? (Once again, at this point, I don't really care if I use the ANSI C Standard I/O or have to use low-level Unix I/O).

War es hilfreich?

Lösung

What you are describing is the standard behavior of read on a file in non-blocking mode.

If there is no data to read it will return -1 with errno set to EAGAIN. You can then go about doing something else for awhile.

If there is data to read it will return how much was read.

If there is no possibility of reading more data (because of eof on a file or the closing of the write end of a pipe or whatnot) then it returns 0.

You can set non-blocking mode either as a parameter to open or via fcntl.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top