Reputation: 43
With this operation I expected to get an error because I'm reading from nothing, but in fact the program seems to keep attempting to read until someone writes to it. If there are no writes it will be stuck in an indefinite loop trying to read and will not proceed.
What exactly happens behind the scene here, do the function kept looping, or is it waiting for a signal, or is something else going on? Is it still taking CPU resources?
Also, is it possible to make the program return an error code/print out something when trying to read without any writes? I don't really need to do it, just wondering if it's possible.
Upvotes: 2
Views: 4091
Reputation: 58132
This is normal behavior. If nothing is available to read, the reading process will block until there is. It will not consume CPU time while blocking; the OS will put it to sleep until another process writes to the pipe.
Keep in mind that pipes were designed to be somewhat transparent; a simple filter-type program should not have to care whether the input is a file or a pipe. If every program that wanted to be able to read from a pipe (think grep
) had to include special handling to wait until the writer was ready, it would be very tedious for those programmers. This behavior means that reading from pipes doesn't require doing anything special.
If you don't want to block if no data is available, you can set the O_NONBLOCK
status flag on the file descriptor, either when you open(2)
it, or with fcntl(fd, F_SETFL, ...)
. In this case, when no data is available, read(2)
will return -1
and set errno
to EAGAIN
or EWOULDBLOCK
. This means, of course, that every time you read from the file descriptor, you have to write code to handle such a case.
You can also use select(2)
or poll(2)
to wait until data is available, optionally with a timeout.
It is also possible to arrange it so that a signal arriving during the blocking will cause read(2)
to return -1
and set errno
to EINTR
. This depends on system call restarting semantics and is a little bit complicated.
Upvotes: 3