2014-01-08 25 views
2

KornShell(ksh)腳本如何退出/終止從另一個ksh腳本啓動的所有進程?退出所有被調用的KornShell(ksh)腳本

如果scriptA.ksh調用scriptB.ksh然後將下面的代碼工作不夠好,但有這個更好的解決辦法?:

scriptA.ksh:

#call scriptBSnippet 
scriptBSnippet.ksh ${a} 

scriptB。 KSH:

#if error: exit this script (scriptB) and calling script (scriptA)# 
kill ${PPID} 
exit 1 

要添加的複雜性,如果SCRIPTA調用scriptB什麼它要求SCR iptC,那麼如果在scriptC中出現錯誤,如何退出所有三個腳本?

scriptA.ksh:

#call scriptBSnippet 
scriptBSnippet.ksh ${a} 

scriptB.ksh:

#if error: exit this script (scriptB) and calling script (scriptA)# 
kill ${PPID} 
exit 1 

scriptC.ksh:

#if error: exit this script (scriptC) and calling scripts (scriptA, scriptB)# 
#kill ${PPID} 
#exit 1 

在感謝提前。

回答

1

殺死由同一腳本啓動的所有進程是一種暴力方法。

最好在進程之間有一些方法可以讓它們正常關閉。

但是,如果所有的過程都是一樣的進程組中,您可將信號發送到整個進程組:

kill -${Signal:?} -${Pgid:?} 

注意兩個參數在這種情況下需要。從-開始的一個參數總是被解釋爲一個信號。

運行一些測試以查看進程組中包含哪些進程。

parent.sh:

Shell=ksh 
($Shell -c :) || exit 

$Shell child1.sh & pid1=$! 

$Shell child2.sh & pid2=$! 

$Shell child3.sh & pid3=$! 

ps -o pid,sid,pgid,tty,cmd $PPID $$ $pid1 $pid2 $pid3 
exit 

child.sh:

sleep 50 

如果從終端運行parent.sh - 它會成爲領導者的過程。

granny.sh:

Shell=ksh 
($Shell -c :) || exit 

$Shell parent.sh & 

wait 
exit 

如果你從另一個腳本運行granny.shparent.sh,然後將進程組領導者,當您使用kill -SIG -PGID方法將包括在內。

另請參閱: What are 「session leaders」 in ps?關於會話和進程組的一些背景知識。

+0

這些ksh腳本(scriptA,scriptB,scriptC)應儘可能分離,每個腳本應儘可能少地使用輸入參數。此解決方案將需要添加輸入參數... – javaPlease42

+1

此解決方案絕對需要更多工作。 –

+0

如果每個腳本都可以將自己放在同一個進程組(Pgid)中,那麼這可能會起作用,那麼有關如何做到這一點的任何見解? – javaPlease42

相關問題