程式扎記: [Linux 常見問題] Shell - WAIT for “any process” to finish

標籤

2016年2月25日 星期四

[Linux 常見問題] Shell - WAIT for “any process” to finish

Source From Here
Question
Is there any built-in feature in bash to wait for any process to finish? The wait command only allows one to wait for child processes to finish. I would like to know if there is any way to wait for any process to finish before proceeding in any script. A mechanical way to do this is as follows but I would like to know if there is any built in feature in bash:
- waitProc.sh
  1. #!/bin/sh  
  2. while ps -p $1 > /dev/nulldo  
  3.     echo -e "Wait PID=$1..."  
  4.     sleep 1;  
  5. done  
  6. echo -e "Exit Shell"  
Usage example:
# groovy wait.groovy & // This script will sleep 20 seconds in background
[1] 28572 // The PID of running groovy script
Wait 20 sec...
# ./waitProc.sh 28572 // This script will wait for PID=28572
Wait PID=28572...
...
Bye!
Exit Shell
[1]+ Done groovy wait.groovy


How-To
There's no builtin. Use kill -0 in a loop for a workable solution:
- waitProc2.sh
  1. #!/bin/sh  
  2. waitPID(){  
  3.     while kill -0 "$1" >> /dev/null 2>&1do  
  4.         sleep 0.5  
  5.     done  
  6. }  
  7.   
  8. echo -e "Wait PID=$1..."  
  9. $(waitPID $1)  
  10. echo -e "Exit Shell..."  
As noted by several commentators, if you want to wait for processes that you do not have the privilege to send signals to, you have found some other way to detect if the process is running to replace the kill -0 $pidcall. On Linux, test -d "/proc/$pid" works, on other systems you might have to use pgrep (if available) or something like ps | grep ^$pid.

Usage example:
# groovy wait.groovy &
[1] 29042
...

# ./waitProc2.sh 29042
Wait PID=29042...
Bye!
Exit Shell...
[1]+ Done groovy wait.groovy


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!