如果正确退出,则终止而非终止过程



我有一个简单的bash脚本,我写这个脚本是为了简化我正在做的一些工作。它所需要做的就是启动一个进程process_1作为后台进程,然后启动另一个进程,process_2。一旦process_2完成,则我需要终止process_1

process_1启动一个程序,除非它收到终止信号,或者当我自己运行它时,它不会真正停止。程序通过{program} {args} > output_file 输出到文件中

process_2可能需要任意的时间,这取决于它所给出的参数。

代码:

#!/bin/bash
#Call this on exit to kill all background processes
function killJobs () {
    #Check process is still running before killing
    if kill -0 "$PID"; then
            kill $PID
    fi
}

检查给定的参数是否有效。。。

#Start process_1
eval "./process_1 ${Arg1} ${Arg2} ${Arg3}" &
PID=$!
#Lay a trap to catch any exits from script
trap killJobs TERM INT
#Start process_2 - sleep for 5 seconds before and after
#Need space between process_1 and process_2 starting and stopping
sleep 5
eval "./process_2 ${Arg1} ${Arg2} ${Arg3} ${Arg4} 2> ${output_file}"
sleep 5
#Make sure background job is killed on exit
killJobs

我通过检查process_1的输出文件来检查它是否已终止。在我的脚本结束后,它仍在更新中。

如果我运行脚本,然后按CTRL+C,脚本将终止,process_1也将终止,输出文件将不再更新。

如果我让脚本在没有干预的情况下运行到完成,process_2和脚本都会终止,但当我检查process_1的输出时,它仍在更新中。

为了检查这一点,我在process_1启动后放了一个echo语句,在killJobs的if语句中放了另一个,所以只有在调用kill $PID时才会回显。

这样我可以看到,退出的两种方式都启动process_1,然后也输入if语句来杀死它。然而,在正常退出的情况下,kill实际上并没有杀死进程。也没有生成错误消息。

您正在备份eval而不是process_1,后者设置$!到脚本本身的PID,而不是到process_1。更改为:

#!/bin/bash
#Call this on exit to kill all background processes
function killJobs () {
    #Check process is still running before killing
    if kill -0 "$PID"; then
            kill $PID
    fi
}
...Check given arguments are valid...
#Start process_1
./process_1 ${Arg1} ${Arg2} ${Arg3} &
PID=$!
#Lay a trap to catch any exits from script
trap killJobs TERM INT
#Start process_2 - sleep for 5 seconds before and after
#Need space between process_1 and process_2 starting and stopping
sleep 5
./process_2 ${Arg1} ${Arg2} ${Arg3} ${Arg4} 2> ${output_file}
sleep 5
#Make sure background job is killed on exit
killJobs

最新更新