魏长东

weichangdong

shell wait命令

wait我的理解是,等多个进程执行完,之后在执行wait后面的脚本。

#!/bin/bash

  for ((i=0;i<5;i++));do

  {

  sleep 3;echo 1>>aa && echo "done!"

  }

  done

  wait

  cat aa|wc -l

  rm aa

  这种情况下,程序顺序执行,每个循环3s,共需15s左右。

  $ time bash test.sh

  done!

  done!

  done!

  done!

  done!

  5

  real    0m15.030s

  user    0m0.002s

  sys     0m0.003s

实例二:“多进程”实现

  #!/bin/bash

  for ((i=0;i<5;i++));do

  {

  sleep 3;echo 1>>aa && echo "done!"

  } &

  done

  wait

  cat aa|wc -l

  rm aa

  这个实例实际上就在上面基础上多加了一个后台执行&符号,
此时应该是5个循环任务并发执行,最后需要3s左右时间。

  $ time bash test.sh

  done!

  done!

  done!

  done!

  done!

  5

  real    0m3.011s

  user    0m0.002s

  sys     0m0.004s

  效果非常明显。

  这里需要说明一下wait的左右。wait是等待前面的后台任务全部完成才往下执行,
否则程序本身是不会等待的,这样对后面依赖前面任务结果的命令来说就可能出错。
例如上面wc -l的命令就报错:不存在aa这个文件。

  wait命令的官方解释如下:

  wait [n]

  Wait for the specified process and return its termination status. 
 n may be a process ID or  a  job  specification; if a job spec is given, 
all processes in that job's pipeline are waited for.  If n is not given, 
all currently active child processes are waited for, and the return status is zero. 
 If  n  specifies  a  non-existent process  or job, the return status is 127. 
 Otherwise, the return status is the exit status of the last processor job waited for.