我有一个简单的bash脚本,我已经编写它来简化我正在做的一些工作。它需要做的只是启动一个进程process_1
作为后台进程然后启动另一个进程process_2
。完成process_2
后,我需要终止process_1
。
process_1
启动一个程序,除非它收到kill信号,否则实际上不会停止,或者当我自己运行它时,CTRL + C.该程序通过{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语句来终止它。然而,杀戮实际上并没有在正常退出的情况下杀死进程。也不会产生错误消息。
答案 0 :(得分:1)
您正在设置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