Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do making processes with & (in bash) and killing them work?

Tags:

bash

process

I have a script that launches another script in the background, and then terminates it. I was expecting the child script to be gone, but in the end it still manages to print some output. Here is the example:

in script one.sh:

echo "this is one"
./two.sh &
sleep 1
pid=$!
kill $pid
echo "this was one"

in script two.sh:

echo "this is two"
./three.sh
echo "this was two"

in script three.sh:

echo "this is three"
sleep 5
echo "this was three"

I ran ./one.sh which is supposed to run two.sh in the background, which in turn runs three.sh but not in the background! The output is get is:

this is one
this is two
this is three
this was one
this was three

Shouldn't "this was three" not appear in the output since three.sh was not ran in the background and two.sh was terminated by one.sh? Could you also point me towards any documentation that describes how processes behave when (not) in background and what happens when they are terminated?

Thank you very much for all your help!

like image 421
George Flourentzos Avatar asked Jun 28 '13 15:06

George Flourentzos


1 Answers

When you start a new process from a bash script this is basically done via fork() .

The new process, referred to as the child, is an exact duplicate of the calling process, referred to as the parent (except for a number of points that can be found in man fork).

If a parent dies the child becomes a child of the init process. Then it is the role of the init process to collect the return code of the child (reaping) after it has exited. So when you kill "two", "three" isn't killed but just gets a different parent. And this is the reason for the trailing three.

The question is discussed from a C-point-of-view here : How to make child process die after parent exits?

like image 122
kamjagin Avatar answered Nov 16 '22 01:11

kamjagin