3 ms·
If you suspect a race condition between two operations, one way of testing it is to add a sleep command to one side or the other. For example: (sleep 1; ech
by derekp7 8y ago
If you suspect a race condition between two operations, one way of testing it is to add a sleep command to one side or the other. For example:
(sleep 1; echo red; echo green 1>&2) | echo blue
vs
(echo red; echo green 1>&2) | (sleep 1; echo blue)
- mjevans 8y agoOffhand I'm unsure of the semantics of sleep... It appears that sleep (at least on a typical modern Linux desktop) does behave similarly to echo in that it does nothing with the pipeline instead of echoing it to terminal. It's curious because someone might assume the default behavior would be to forward all file descriptors unless something was done to the data-streams. Clearly that isn't the case, the shell ties the prior standard output to the next programs standard input irrespective of if anything ever happens to it.
- jstimpfle 8y agoI don't know what you mean by "forward" but I have the impression you don't understand how file descriptors (i.e. "open files or streams") work. The shell sets up a pipe and connects the left side to the pipe's writing end, and the right side to the reading end. Now, the right side is actually a subshell (indicated by the parentheses "(...)"). And that subshell can spawn as many other processes, sequentially or in parallel, as it wants. All of them will get the open file descriptor (the pipe's reading end) inherited by the operating system. If you had multiple processes in parallel reading from the pipe, the outcome would be totally nondeterministic (dependent on the kernel's scheduling behaviour. In the example case, none of the potential readers actually read (not the subshell itself, not the sleep, and not the echo). Here's a perhaps illuminating example: (echo h; echo hello; echo HALLO; ) | ( read firstline; echo "Firstline is $firstline"; grep A; ) Does that help?