Having seen the code (unfair advantage), the primary problem was the process structure combined with not closing pipes thoroughly.
The process structure for a pipeline ps | sort
was:
main shell
- coordinator sub-shell
- ps
- sort
The main shell was creating N pipes (N = 1 for ps | sort
). The coordinator shell was then created; it would start the N+1 children. It did not, however, wait for them to terminate, nor did it close its copy of the pipes. Nor did the main shell close its copy of the pipes.
The more normal process structure would probably do without the coordinator sub-shell. There are two mechanisms for generating the children. Classically, the main shell would fork one sub-process; it would do the coordination for the first N processes in the pipeline (including creating the pipes in the first place), and then would exec the last process in the pipeline. The main shell waits for the one child to finish, and the exit status of the pipeline is the exit status of the child (aka the last process in the pipeline).
More recently, bash
provides a mechanism whereby the main shell gets the status of each child in the pipeline; it does the coordination.
The primary fixes (apart from some mostly minor compilation warnings) were:
- main shell closes all pipes after forking coordinator.
- main shell waits for coordinator to complete.
- coordinator closes all pipes after forking pipeline.
- coordinator waits for all processes in pipeline to complete.
- coordinator exits (instead of returning to provide duelling dual prompts).
A better fix would eliminate the coordinator sub-shell (it would behave like the classical system described).
sort
inps | sort
) has its standard output left unredirected. When that child process writes, it writes to its standard output, which is the same as the standard output of the shell itself. (Obviously, if you writeps | sort > file
, then the output goes to the file instead.) The child process has its standard output flushed automatically before it dies; there's nothing for you to do. – Jonathan Leffler