我从shell脚本启动了一个后台进程,我想在脚本结束后终止该进程。
如何从我的shell脚本中获取此过程的PID? 据我所见变量$!
包含当前脚本的PID,而不是后台进程。
#1楼
您也许还可以使用pstree:
pstree -p user
通常,这会为“用户”提供所有进程的文本表示形式,而-p选项会给出进程ID。 据我了解,它并不依赖于当前Shell拥有进程。 它还显示了叉子。
#2楼
这就是我所做的。 检查一下,希望对您有所帮助。
#!/bin/bash
#
# So something to show.
echo "UNO" > UNO.txt
echo "DOS" > DOS.txt
#
# Initialize Pid List
dPidLst=""
#
# Generate background processes
tail -f UNO.txt&
dPidLst="$dPidLst $!"
tail -f DOS.txt&
dPidLst="$dPidLst $!"
#
# Report process IDs
echo PID=$$
echo dPidLst=$dPidLst
#
# Show process on current shell
ps -f
#
# Start killing background processes from list
for dPid in $dPidLst
do
echo killing $dPid. Process is still there.
ps | grep $dPid
kill $dPid
ps | grep $dPid
echo Just ran "'"ps"'" command, $dPid must not show again.
done
然后只需以适当的权限将其运行为: ./bgkill.sh
root@umsstd22 [P]:~# ./bgkill.sh
PID=23757
dPidLst= 23758 23759
UNO
DOS
UID PID PPID C STIME TTY TIME CMD
root 3937 3935 0 11:07 pts/5 00:00:00 -bash
root 23757 3937 0 11:55 pts/5 00:00:00 /bin/bash ./bgkill.sh
root 23758 23757 0 11:55 pts/5 00:00:00 tail -f UNO.txt
root 23759 23757 0 11:55 pts/5 00:00:00 tail -f DOS.txt
root 23760 23757 0 11:55 pts/5 00:00:00 ps -f
killing 23758. Process is still there.
23758 pts/5 00:00:00 tail
./bgkill.sh: line 24: 23758 Terminated tail -f UNO.txt
Just ran 'ps' command, 23758 must not show again.
killing 23759. Process is still there.
23759 pts/5 00:00:00 tail
./bgkill.sh: line 24: 23759 Terminated tail -f DOS.txt
Just ran 'ps' command, 23759 must not show again.
root@umsstd22 [P]:~# ps -f
UID PID PPID C STIME TTY TIME CMD
root 3937 3935 0 11:07 pts/5 00:00:00 -bash
root 24200 3937 0 11:56 pts/5 00:00:00 ps -f
#3楼
pgrep
可以为您获取父进程的所有子PID。 如前所述, $$
是当前脚本的PID。 因此,如果您希望脚本在执行后自行清理,则可以做到这一点:
trap 'kill $( pgrep -P $$ | tr "\n" " " )' SIGINT SIGTERM EXIT
#4楼
您可以使用jobs -l
命令转到特定的jobL
^Z
[1]+ Stopped guard
my_mac:workspace r$ jobs -l
[1]+ 46841 Suspended: 18 guard
在这种情况下,46841是PID。
来自help jobs
:
-l报告作业的进程组ID和工作目录。
jobs -p
是另一个仅显示PID的选项。
#5楼
-
$$
是当前脚本的pid -
$!
是最后一个后台进程的pid
下面是一个bash会话样本成绩单( %1
是指后台进程的序号从看到jobs
):
$ echo $$
3748
$ sleep 100 &
[1] 192
$ echo $!
192
$ kill %1
[1]+ Terminated sleep 100
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/3178704