在 bash 脚本中,如何从使用 eval 命令时执行的程序中获取 PID?
我在 bash 脚本中有与此类似的命令:
eval "( java -classpath ./ $classname ${arguments[@]} $redirection_options $file )" &
pid=$!
但是,如果我执行 ps $pid ,它会显示主脚本进程而不是 java 程序的进程。
当我省略 eval 时,它会获得正确的过程,但为了让一些复杂的参数正常工作,我需要使用它。
知道如何在 eval 命令中执行 java 程序时获取它的 PID 吗?
I have commands in a bash script that are similar to this:
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.
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.
Any idea of how I can get the PID of the java program when it's executed within an eval command?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的&符号正在
eval
行后台运行,导致(顶级)shell分叉一个子shell,子shelleval
字符串,然后将您的java程序运行为顶级 shell 的孙子。因此,$!
报告子 shell 的 pid,它是最近的后台命令。相反,将背景移动到您的 eval 中:
只要括号没有变得复杂到足以成为子shell,上面的内容就可以工作。
Your ampersand is backgrounding the
eval
line, causing the (top-level) shell to fork a child, the child shell toeval
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.Instead move the backgrounding inside your eval:
As long as the parenthetical doesn't get complicated enough to become a subshell, the above will work.