Suppose two processes (or threads) both call write on a pipe/socket/terminal whose buffer is full, thus blocking. Is there any guarantee as to who gets to write first when buffer space becomes available? Is it FIFO order? Globally, or within a given priority level, and ordered first by priority? Or is it completely random/indeterminate?
What about starved reads? Will the first to call read get the data when it becomes available?
I’m asking specifically on Linux and as far as I know POSIX has nothing to say about these issues, but I’d also be interested if I’m wrong on that and POSIX does mandate particular behaviors.
Within the kernel, the
pipe_wait()function is used by both pipe readers and writers to block. This function uses theDEFINE_WAIT()macro to define a wait queue, which sets the.flagsmember of the wait queue to zero.They are woken up with a call to
wake_up_interruptible_sync_poll(), which calls down to__wake_up_common(). You can see that if the.flagsmember does not have theWQ_FLAG_EXCLUSIVEbit set (as in this case), then all waiters are unceremoniously made runnable.The scheduler will then use its normal heuristics to pick the runnable processes to run next. In particular, a later waiter with a higher priority will get to go first – but note that if you have more than one processor core available, multiple waiters can start to run simultaneously, and which one actually gets to touch the pipe first depends entirely on which one manages to grab the pipe lock first.