2016-03-22 97 views
0

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

process_1启动一个程序,它实际上并没有停止,除非它收到的终止信号,或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开始之后加上了一个回声语句,而另一个在killJobs的if语句中,所以只有在调用kill $PID时才会回显。

这样做,我可以看到退出的两种方式启动process_1,然后又进入if语句来杀死它。然而,在正常退出的情况下,kill并不会真正杀死进程。也不会产生错误信息。

+0

有点偏离主题,但为什么在这里使用''''eval'''? – dekkard

+0

我想知道如何执行一个程序,就像你会形成终端一样,这就是我在网上找到的解决方案。如果另一种方式更好,我愿意接受建议。 – Grailor

回答

1

你backgrounding的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 
+0

这没有奏效,我仍然遇到同样的问题 – Grailor

+0

我已经更新了答案。那样有用吗? – webb

+0

仍然没有工作,不幸的是 – Grailor