Bash-一个脚本有两个进程 [英] Bash - Two processes for one script

查看:101
本文介绍了Bash-一个脚本有两个进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为test.sh的shell脚本:

I have a shell script, named test.sh :

#!/bin/bash
echo "start"
ps xc | grep test.sh | grep -v grep | wc -l
vartest=`ps xc | grep test.sh | grep -v grep | wc -l `
echo $vartest
echo "end"

输出结果是:

start
1
2
end

所以我的问题是,当我使用``调用ps时(为什么$()会发生这种情况),而不是直接调用ps时为什么不运行两个test.sh进程?如何获得所需的结果(1)?

So my question is, why are there two test.sh processes running when I call ps using `` (the same happens with $()) and not when I call ps directly? How can I get the desired result (1)?

推荐答案

启动子shell时,与反引号一样,bash会分叉自身,然后执行要运行的命令.然后,您还运行一个管道,使所有这些管道都在各自的子shell中运行,因此最终得到了脚本的额外"副本,该副本等待管道完成,以便可以收集输出并将其返回给原始脚本.

When you start a subshell, as with the backticks, bash forks itself, then executes the command you wanted to run. You then also run a pipeline which causes all of those to be run in their own subshells, so you end up with the "extra" copy of the script that's waiting for the pipeline to finish so it can gather up the output and return that to the original script.

我们将使用(...)进行一些实验,以在子shell中显式运行进程,并使用执行 ps |的 pgrep 命令.grep名称" |grep -v grep 给我们,只是向我们展示了与字符串匹配的过程:

We'll do a little expermiment using (...) to run processes explicitly in subshells and using the pgrep command which does ps | grep "name" | grep -v grep for us, just showing us the processes that match our string:

echo "Start"
(pgrep test.sh)
(pgrep test.sh) | wc -l
(pgrep test.sh | wc -l)
echo "end"

对我而言,这会产生输出:

which on a run for me produces the output:

Start
30885
1
2
end

因此,我们可以看到在子外壳程序中运行 pgrep test.sh 只会找到test.sh的单个实例,即使该子外壳程序是管道本身的一部分也是如此.但是,如果子shell包含管道,那么我们将获得脚本的分叉副本,以等待管道完成

So we can see that running pgrep test.sh in a subshell only finds the single instance of test.sh, even when that subshell is part of a pipeline itself. However, if the subshell contains a pipeline then we get the forked copy of the script waiting for the pipeline to finish

这篇关于Bash-一个脚本有两个进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆