Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Child processes in bash

Tags:

linux

bash

We use bash scripts with asynchonous calls using '&'. Something like this:

function test() {
   sleep 1
} 
test &
mypid=$!
# do some stuff for two hours
wait $mypid 

Usually everything is OK, but sometimes we get error

"wait: pid 419090 is not a child of this shell"

I know that bash keeps child pids in a special table and I know ('man wait') that bash is allowed not to store status information in this table if nobody uses $!, and nobody can state 'wait $mypid'. I suspect, that this optimization contains a bug that causes the error. Does somebody know how to print this table or how to disable this optimization?

like image 545
Alexey Sokirko Avatar asked Nov 09 '22 21:11

Alexey Sokirko


1 Answers

I was trying recently something quite similar. Are you sure that the second process you run concurrently starts before the previous dies? In this case, I think that there is a possibility it takes the same pid with the recently died one.

Also I think we cannot be sure that $! takes the pid of the process we lastly run, because there may be several processes in the background from another functions starting or ending at the same time.

I would suggest using something like this.

mypid=$(ps -ef | grep name_of_your_process | awk ' !/grep/ {print $2} ')

In grep name_of_your_process you can specify some parameters too so as to get the exact process you want.

I hope it helps a bit.

like image 65
iwita Avatar answered Nov 15 '22 06:11

iwita