- 论坛徽章:
- 0
|
The process will block on the read end (i.e. cat) since someone has the write side open.- 1794 -bash
- 3842 /bin/bash ./test.sh --------------> Main shell script
- 3880 /bin/bash ./test.sh ------> Left side of the pipe (write end) in subshell
- 3881 sleep 5
- 3882 /bin/bash ./test.sh ------> Right side of the pipe (read end) in subshell
- 3883 cat
复制代码 If the stdout is closed, the 'cat' is returned immediately instead of waiting.
But of course, as we have already closed stdout, "echo 3" will fail.- { echo '1'; exec 1>&-; sleep 5; echo '3'; } | { cat; echo '2'; sleep 1; }
- root@server:~$ ./test.sh
- Time: 0
- 1
- 2
- ./test.sh: line 6: echo: write error: Bad file number
- Time: 5
复制代码 To make "echo 3" to print output, one way is to save the stdout first and then restore it later.
(There may be better ways to do it.)- exec 3>&1
- { echo '1'; exec 1>&-; sleep 5; exec 1>&3 3>&-; echo '3'; } | { cat; echo '2'; sleep 1; }
- exec 3>&-
- root@server:~$ ./test.sh
- Time: 0
- 1
- 2
- 3
- Time: 5
复制代码 |
|