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


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...