Friday, October 28, 2011

Stop waiting on wait

If you have gone through one of your scripts and concluded that the only way to make sure that all necessary child processes have completed is to either use "wait" or sleep <really large number> I have something for you. If not, just ignore this, its probably for a few niche scripters anyways.

Here is a function I call wait_pids in an example script:

 #!/bin/sh  
 #copyright 2011 Brad Conroy - redistributable under the UIUC license  
 #wait_pids is a function to replace wait when you only need to wait for some  
 #not all child processes (ex. speeding up init, or other custom scripts)  
   
 wait_pids(){  
 #this squeezes separators into spaces  
 PIDS=`echo $@`  
   
 #string replacement is not posix but is in most shells, so use it vs. sed  
 PIDS="[ -d /proc/"${PIDS// / ] || [ -d /proc/}" ]"  
   
 #each process gets a directory with its process id in /proc  
 while (`eval $PIDS`) ; do  
   
 #we don't like the taste of cpus, so lets not eat them - feel free to tweak  
 usleep 1000  
   
 #uncomment/tweak the next line if you want to see an indicator while waiting  
 #printf .  
 done  
 }  
   
 #just a test program to fork so we can get a test pid  
 xmessage 11111111111111111111111 &  
 #the $! gives the process id of the last command  
 FIRST=$!  
   
 #a second program so we know whether it works for multiple processes  
 xmessage 2222222222222222222222222 &  
 SECOND=$!  
   
 wait_pids $FIRST $SECOND  

Note that any amount of code can be in between the child processes

No comments:

Post a Comment