在 bash 脚本中,如何从使用 eval 命令时执行的程序中获取 PID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4339756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inside a bash script, how to get PID from a program executed when using the eval command?
提问by Milo
I have commands in a bash script that are similar to this:
我在 bash 脚本中有与此类似的命令:
eval "( java -classpath ./ $classname ${arguments[@]} $redirection_options $file )" &
pid=$!
However if I do a ps $pid
it shows the main script process instead of the process of the java program.
但是,如果我这样做,ps $pid
它会显示主脚本进程而不是 java 程序的进程。
It obtains the correct process when I omit the eval, but in order to get some of the complicated arguments to work correctly I need to use it.
当我省略 eval 时,它会获得正确的过程,但是为了让一些复杂的参数正常工作,我需要使用它。
Any idea of how I can get the PID of the java program when it's executed within an eval command?
知道在 eval 命令中执行时如何获取 java 程序的 PID 吗?
回答by pilcrow
Your ampersand is backgrounding the eval
line, causing the (top-level) shell to fork a child, the child shell to eval
the string and in turn run your java program as a grandchild of the top-level shell. So, $!
reports the pid of the child shell, which is the most recently backgrounded command.
您的 & 符号是该eval
行的背景,导致(顶级)shell 派生子,子 shell 到eval
字符串,然后将您的 java 程序作为顶级 shell 的孙子运行。因此,$!
报告子 shell 的 pid,这是最近后台运行的命令。
Instead move the backgrounding inside your eval:
而是在您的 eval 中移动背景:
eval "(java ...) &"
pid=$!
As long as the parenthetical doesn't get complicated enough to become a subshell, the above will work.
只要括号没有变得足够复杂以成为subshell,上述内容就可以工作。