linux 脚本 结束进程,当shell脚本退出时,如何终止后台进程/作业?

#!/bin/bash

# killable-shell.sh: Kills itself and all children (the whole process group) when killed.

# Adapted from http://stackoverflow.com/a/2173421 and http://veithen.github.io/2014/11/16/sigterm-propagation.html

# Note: Does not work (and cannot work) when the shell itself is killed with SIGKILL, for then the trap is not triggered.

trap "trap - SIGTERM && echo 'Caught SIGTERM, sending SIGTERM to process group' && kill -- -$$" SIGINT SIGTERM EXIT

echo $@

"$@" &

PID=$!

wait $PID

trap - SIGINT SIGTERM EXIT

wait $PID

IT工作示例:

$ bash killable-shell.sh sleep 100

sleep 100

^Z

[1] + 31568 suspended bash killable-shell.sh sleep 100

$ ps aux | grep "sleep"

niklas 31568 0.0 0.0 19640 1440 pts/18 T 01:30 0:00 bash killable-shell.sh sleep 100

niklas 31569 0.0 0.0 14404 616 pts/18 T 01:30 0:00 sleep 100

niklas 31605 0.0 0.0 18956 936 pts/18 S+ 01:30 0:00 grep --color=auto sleep

$ bg

[1] + 31568 continued bash killable-shell.sh sleep 100

$ kill 31568

Caught SIGTERM, sending SIGTERM to process group

[1] + 31568 terminated bash killable-shell.sh sleep 100

$ ps aux | grep "sleep"

niklas 31717 0.0 0.0 18956 936 pts/18 S+ 01:31 0:00 grep --color=auto sleep

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值