From this post it sounds like fgets()
is meant to be a blocking call, however, this man page shows that if set as non-blocking, it will return NULL
and errno
would be EWOULDBLOCK
if no data is ready to be read, so my assumption is that it is indeed possible to use it as non-blocking.
I'm aware of select()
and friends, I'd just like to know if it's safe to use it as non-blocking? and if it's not, what are those reasons?
I'd just like to know if it's safe to use it as non-blocking? and if it's not, what are those reasons?
It depends on what you mean by "safe". C itself has no concept of non-blocking I/O, so if you're writing code that must be widely portable then even supposing that non-blocking I/O is an available alternative is unsafe.
If you're writing for a more specific environment, for example a POSIX environment, then you may be able to rely on the availability of non-blocking I/O, but you should consider the specifications of that environment to determine what behavior you may be able to expect from fgets()
when the file you specify to it is, in some relevant sense, in non-blocking mode. POSIX does specify that fgets()
shall fail with an error under the same conditions that fgetc()
does, one of which is that
The
O_NONBLOCK
flag is set for the file descriptor underlying stream and the thread would be delayed in the [fgets()
] operation.
With that being the case, if you're defining "safe" as "specified by POSIX" then yes, relying on fgets()
not to block when the underlying underlying open file description is in non-blocking mode is safe.
@R.. asserts in comments that that using stdio functions on a file that is in non-blocking mode may produce data loss. That's plausible, but I have not yet found the basis for that assertion. I'm not prepared to contradict him on that point, however, so again, whether what you propose is "safe" depends on just what you mean by that term.