The order in which pipeline components are executed in shell

こ雲淡風輕ζ 提交于 2021-01-20 06:52:08

问题


ls | wc

In which order ls and wc executed here? Or, are | and wc just arguments to ls?


回答1:


In the expression ls | wc, your shell will perform roughly the following actions:

  1. start two subshells A and B, with A's standard output connected to B's standar input.
  2. In subshell A, start the command ls
  3. In subshell B, start the command wc
  4. wait until all subshells terminated
  5. set $? to the exit status of subshell B (i.e. the exit status of wc)

The bash manpage has more details:

Pipelines

A pipeline is a sequence of one or more commands separated by one of the control operators | or |&. The format for a pipeline is:

[time [-p]] [ ! ] command [ [|│|&] command2 ... ]

The standard output of command is connected via a pipe to the standard input of command2. This connection is performed before any redirections specified by the command (see REDIRECTION below). If |& is used, the standard error of command is connected to command2's standard input through the pipe; it is shorthand for 2>&1 |. This implicit redirection of the standard error is performed after any redirections specified by the command.

The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. If pipefail is enabled, the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully. If the reserved word ! precedes a pipeline, the exit status of that pipeline is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value.

If the time reserved word precedes a pipeline, the elapsed as well as user and system time consumed by its execution are reported when the pipeline terminates. The -p option changes the output format to that specified by POSIX. The TIMEFORMAT variable may be set to a format string that specifies how the timing information should be displayed; see the description of TIMEFORMAT under Shell Variables below.

Each command in a pipeline is executed as a separate process (i.e., in a subshell).




回答2:


No,ls not handle the pipe argument,this done by shell.

The content of stdout of ls command was, taken as input of wc from stdin.

ls [stdout]|* [stdin]* wc -l

the command wc will get that stdout content as input.

Here both commands are executed as different process by shell. which means both have different PID.

For Verify youself this answer,use ps|cat. you can see that different process cat and ps.

  PID TTY          TIME CMD
11695 pts/1    00:00:00 bash
12207 pts/1    00:00:00 ps
12208 pts/1    00:00:00 cat


来源:https://stackoverflow.com/questions/33462120/the-order-in-which-pipeline-components-are-executed-in-shell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!