dcc*_*310 2 parallel-processing bash
我正在查看http://tldp.org/LDP/abs/html/subshel ls.html,其中提到子shell可用于并行化任务。然后他们给出了例子:
Run Code Online (Sandbox Code Playgroud)(cat list1 list2 list3 | sort | uniq > list123) & (cat list4 list5 list6 | sort | uniq > list456) & # Merges and sorts both sets of lists simultaneously. # Running in background ensures parallel execution. # # Same effect as # cat list1 list2 list3 | sort | uniq > list123 & # cat list4 list5 list6 | sort | uniq > list456 &
wait # Don't execute the next command until subshells finish.
diff list123 list456
Run Code Online (Sandbox Code Playgroud)
前两个命令不会与后两个命令大致同时完成吗?我原以为最后两个命令也会并行执行,并且通过一些sleep循环,我无法创建它们不同的情况。最后两个命令与前两个命令有何不同?如果它们没有不同,那么为什么将子 shell 作为并行化方法被提及,而将进程放在后台也可以完成同样的任务呢?
事实上,两者:
c1 | c2 & # where c1 and c2 are arbitrary commands
Run Code Online (Sandbox Code Playgroud)
和:
(c1 | c2) &
Run Code Online (Sandbox Code Playgroud)
使用子 shell,如下所示:
c1 | c2
Run Code Online (Sandbox Code Playgroud)
没有&. 原因是,一般来说,管道需要创建子shell。
(在一些非常具体的情况下,某些 shell(包括 bash)可以避免创建子 shell:例如,如果您设置了( )并且作业控制未激活,则不会为 bash 中的循环prog | while read ...创建单独的子 shell 。它总是会这样做在其他一些shell中创建一个子shell.这可以通过观察循环中或循环内设置的变量值来看出.但是当命令不是内置的shell时,shell必须在内部创建一个子shell才能把管子挂起来。)whilelastpipeshopt -s lastpipewhilec2