Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I have written a shell script to initiate three background process in the same time. In shell script I am trying to wait for all children to finish their job and then the parent job to terminate. But, with some reason I see the the sleeping processes never awakes.

echo "Starting $1 instances" >> $logfile
for i in `seq 1 $1`
do
        /usr/bin/php index.php name&
done

echo "Waiting for all $l instances to complete \n" >> $logfile
wait
echo "All $instances scripts completed"  >>  $logfile
share|improve this question
1  
While @StevenMonday's answer is the right way to do it, I'd like to point out the "-C" argument to ps. Rather than "ps|grep|grep", you can just do ps -C myscript.sh to find all the processes with that name. –  dannysauer Feb 20 '14 at 15:26
    
The child processes will always appear in ps as zombies because their parent (your script) is spending all its time polling and cannot handle their exit. –  OrangeDog Feb 20 '14 at 17:55

1 Answer 1

If you are using bash, you should use the wait command, rather than an elaborate polling loop. I don't know about other shells (sh, zsh, and so on), but I assume most/all of them also have wait, or an equivalent to it.

share|improve this answer
    
Running just wait is the right way to do this. :) POSIX defines the wait utility for use by a POSIX-compliant shell, so it should be there on any shell that matters. pubs.opengroup.org/onlinepubs/009695399/utilities/wait.html –  dannysauer Feb 20 '14 at 15:22
    
I have updated my script to use wait but now I get "wait: pid 17577 is not a child of this shell".....whats wrong ? –  user269867 Feb 21 '14 at 6:30
    
@user269867: Since I wrote my answer, you have edited your question to replace sleep with wait inside your polling loop. I will repeat my advice, but more clearly this time: Remove the polling loop. As @dannysauer commented, you should just wait. wait without any arguments will wait for all child processes, so you don't need to save child process PIDs. –  Steven Monday Feb 22 '14 at 14:17
    
My intention from this script is to initiate multiple process and then wait to their completion. I have a cron entry with it which is which call this script every min with "2" ..I am confused if I am doing it all right... –  user269867 Feb 24 '14 at 9:20
    
@StevenMonday I have edited my script can you please check if it's right?. I have a question - the wait without argument will wait till parent is not finished? How can I retrieve my script process id in the script? –  user269867 Feb 24 '14 at 9:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.