脚本存在时杀死后台进程 [英] killing background processes when script exists

查看:28
本文介绍了脚本存在时杀死后台进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 scriptA,它将执行另一个将在后台启动的脚本.现在我需要确保当我杀死 scriptA (cmd+c) 时,后台进程也被杀死.

I have scriptA which will execute another script which will startup in the background. Now I need to make sure that when I kill scriptA (cmd+c) that the background processes are also killed.

#!/bin/bash
echo "This script is about to run another script."
  sh ../processes/processb/bin/startserver.sh &
 FOO_PID=$!
 echo "This script has just run another script." $FOO_PID

这个脚本执行得很好,但是一旦我按下 cmd+c 并对 FOO_PID 值执行ps"命令,该进程仍然存在.我做错了什么?

This script executes fine, but once I press cmd+c and do a 'ps' command on FOO_PID value , that process still exists. What am I doing wrong?

更新-----------

UPDATE-----------

所以我尝试了下面的代码,但仍然没有终止 scriptC 的进程.我认为它只是在按下 ctrl+c 时才终止 scriptA(父),因此不会执行陷阱命令?

So I tried out below code, but still scriptC's process is not getting killed. I think it just only terminates scriptA ( parent) when pressed ctrl+c and therefore trap command does not get executed?

     #!/bin/bash

echo "This script is about to run another script."

   ../common/samples/bin/scriptC.sh &
 mypid=$!
kill -0 "$mypid" && echo "My process is still alive."

echo "This script has just run another script." $mypid

trap "kill $mypid && kill $$" INT

推荐答案

SIGINT添加trap:

trap "kill $FOO_PID && kill $$" INT

或者对于任何类型的退出,处理伪信号EXIT:

or for any sort of exiting, handle the pseudo signal EXIT:

trap "kill $FOO_PID && kill $$" EXIT

这篇关于脚本存在时杀死后台进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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