如何获取后台进程的进程ID? [英] How to get process ID of background process?
问题描述
我从shell脚本启动了一个后台进程,我想在脚本结束后终止该进程.
I start a background process from my shell script, and I would like to kill this process when my script finishes.
如何从我的shell脚本中获取此过程的PID?据我所知,变量$!
包含当前脚本的PID,而不是后台进程.
How to get the PID of this process from my shell script? As far as I can see variable $!
contains the PID of the current script, not the background process.
推荐答案
您需要在启动时保存后台进程的PID:
You need to save the PID of the background process at the time you start it:
foo &
FOO_PID=$!
# do other stuff
kill $FOO_PID
您不能使用作业控制,因为它是一种交互式功能,并且与控制终端绑定在一起.脚本不一定要附加终端,因此作业控制不一定可用.
You cannot use job control, since that is an interactive feature and tied to a controlling terminal. A script will not necessarily have a terminal attached at all so job control will not necessarily be available.
这篇关于如何获取后台进程的进程ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!