繁体   English   中英

终止shell脚本后进程未终止

[英]process does not terminate after killing shell script

我有一个shell脚本,可以在不打开新终端的情况下并行执行两个命令

我的剧本

 #!/bin/sh sudo command1 & sudo command2 

我需要一个shell脚本,当我在执行shell脚本的终端中按cntl + c时应终止该脚本

创建一个函数,使用trap在退出时执行。 注册分叉进程的进程ID,并在退出函数中终止该PID。

FORKED_PID=

# this function will be executed when the script is terminated for any reason
function finish() {
    # get the process id of the process with parent process id $FORKED_PID, and kill it
    sudo kill -9 `ps --ppid $FORKED_PID -o pid=`
}
# bind this function to the EXIT signal
trap finish EXIT

# run command1 with sudo
sudo command1 &
# get the process id from the previous command and put it in $FORKED_PID
FORKED_PID=$!
# run command2 with sudo
sudo command2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM