Question

i have a question about linux process, and i can not figure it out.
This problem came from the book “Advanced Bash Script”, code is here: (I have simplified it)

#! /bin/bash
# spawn.sh
sleep 1
sh $0   # fork a child process here and into infinite loop

exit 0  # the script will never come here

when i run ./spawn.sh in the shell, the process will be stuck there, and there will be a lot of "sh spawn.sh" processes there after a while.
i think the relationship among processes now is like:

./spawn.sh process(pid: 10000) ---> child process(pid: 10001) ---> child process(pid:1002) --->child process(pid:1003) ---> and so on

when i push Control-C in the Shell, the parent process is over, and all its child processes are over too. this is where i can not understand. why all child processed perish ? i think the relationship among processes should be like:

init(pid: 1) ---> child process(pid: 10001) ---> child process(pid:1002) --->child process(pid:1003) ---> and so on

But the fact is that as if parent process sends a signal to it child process when it is over, thus cause all child processes perish one by one. Is this normal or a feature of shell script?

thank you very much in advance.

Was it helpful?

Solution

when i push Control-C in the Shell, the parent process is over, and all its child processes are over too. this is where i can not understand. why all child processed perish

When you hit Ctrl-C, SIGINT is sent not only to the parent process but to the entire process group. What this means is that all three processes get a SIGINT, so they die. To see this in action, add a

trap "process $$ exiting" INT

A quick way to see that children don't react to their parents' demise is to have a script spawn a single child and then kill the parent.

OTHER TIPS

Control-C is killing the most recent child, not the original shell. When sh $0 exits, the next line of code causes the current shell to exit as well, which causes a cascade of completed processes all the way back to the original parent.

i think i know the answer now. it is because that Control-C will send SIGINT to not only the shell script process, but also its sub processes. Since these processes do not trap SIGINT, so they are over.
Command kill -2 is not the same as Ctrl-C, for detail, see this: http://ajhaupt.blogspot.com/2011/01/whats-difference-between-ctrl-c-and.html
And thank you all guys help me :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top