Can a process which is writing to a pipe tell when a reader (in a different process) is blocking because it is trying to read from the pipe and the pipe is currently empty?
If this is not possible with a pipe, is it possible with some other form of IPC?
I suspect the answer is no, but I thought I’d ask anyway.
The use case for this is to write to the pipe only when data is really needed by a reader.
As far as I know it is not possible directly (only using a pipe). Even if you know the size of the pipe buffer (you can get by invoking
fpathconf(pipefds[0],_PC_PIPE_BUF))) and you know that it is empty, there is still no guarantie that the other process is actually reading from it. Even if it is reading, it may do it in nonblocking mode. You may try to find out whether the other process is bloked on some system call (e.g.read), but even this would not be helpful (the other process may be reading something else at the moment).The only way that comes to my mind is using process semaphores. This requires that the other (e.g. child) process knows exactly which semaphore to use and how to use it. You can test if the samaphore is locked.