简体   繁体   中英

Exit all called KornShell (ksh) scripts

How can a KornShell (ksh) script exit/kill all the processes started from another ksh script?

If scriptA.ksh calls scriptB.ksh then the following code works good enough, but is there a better solution for this?:

scriptA.ksh:

#call scriptBSnippet
scriptBSnippet.ksh ${a}

scriptB.ksh:

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

To add complexity what if scriptA calls scriptB which calls scriptC, then how to exit out of all three scripts if there is an error in 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

Thanks in advance.

Killing all processes started by the same script is a bit of a brute force method.

It would be best to have some method of communication between the processes that would allow them to gracefully shutdown.

However, if all processes are in the same process group, you can send a signal to the entire process group:

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

Note that two arguments are required in this case. A single argument starting with - is always interpreted as a signal.

Run some tests to see which processes get included in the process group.

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

If you run parent.sh from a terminal - it will become the process leader.

granny.sh:

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

$Shell parent.sh & 

wait
exit

If you run parent.sh from another script granny.sh , then that will be the process group leader, and will be included when you use the kill -SIG -PGID method.

See also this answer to: What are “session leaders” in ps ? for some background on sessions and process groups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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