Reputation: 71
I am a bit confused on how PID's are allocated by BASH shell so I need your help to understand this using a problem which I am trying to resolve here. I am calling a function in a shell script. This function runs another groovy script in background as seen below:
fn_list()
{
... ... ...
groovy list_gn.gy -p $prop_file $@ &
echo "Extracting PID No :$!" >> $logpid
}
I am calling this function like this inside a loop:
for x in `cat $list | grep -v '#'`; do
fn_list &
echo "Extracting function PID No :$!" >> $logpid
done
Since I am running this function in background, and also the groovy which being run by this function runs in background (using &).
My question is that I am logging PID of the function and I am also logging PID of the groovy script which is being calling from inside of this function. Will the PID's for the function and the groovy which is being called from inside this function be different ? And is it a correct way to log the PIDs ?
I am need to understand it's behavior because I am planning to fork the function process 3 times. So want to be absolutely sure if that's a right approach.
Upvotes: 1
Views: 5681
Reputation: 19315
actually pid are not allocated by bash but by the operating system, when a process is forked it is assigned a new pid, calling groovy .. &
from bash process creates a new child process groovy which parent in bash process.
a bash function call doesn't create a new pid because it is run in the same process the same for a builtin command.
However because of the &
after the function call this creates a new bash process (subshell), maybe one of the two &
is not needed.
If you are interessed by the result of these processes you may need to wait for their execution this is what wait
builtin does, a parallel execution could look to.
pids=()
for ... ; do
groovy ... &
pids+=( "$!" )
done
exit_codes=()
for pid in "${pid[@]}"; do
wait "$pid"
exit_codes+=( "$?" )
done
Upvotes: 4