等待和睡眠之间的区别

时间:2012-11-08 20:04:50

标签: bash shell wait sleep

waitsleep之间有什么区别?

5 个答案:

答案 0 :(得分:312)

wait等待一个完成的过程; sleep会睡一段时间。

答案 1 :(得分:98)

wait是一个BASH内置命令。来自man bash

    wait [n ...]
        Wait  for each specified process and return its termination sta-
        tus.  Each 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  pro-
        cesses  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 process or job waited for.

sleep不是shell内置命令。它是一种延迟指定时间的实用程序。

sleep命令可能支持在不同的时间单位等待。 GNU coreutils 8.4 man sleep说:

    SYNOPSIS
        sleep NUMBER[SUFFIX]...

    DESCRIPTION
        Pause for NUMBER seconds.  SUFFIX may be ‘s’ for seconds (the default),
        ‘m’ for minutes, ‘h’ for hours or ‘d’ for days.  Unlike most  implemen-
        tations  that require NUMBER be an integer, here NUMBER may be an arbi-
        trary floating point number.  Given two or more  arguments,  pause  for
        the amount of time specified by the sum of their values.

答案 2 :(得分:82)

sleep只会将shell延迟指定的秒数。

wait使shell等待给定的子进程。 e.g:

workhard &
[1] 27408
workharder &
[2] 27409
wait %1 %2

延迟shell,直到两个子进程都完成

答案 3 :(得分:22)

Bash

wait命令停止脚本执行,直到所有在后台运行的作业终止 或直到指定为选项的作业号或进程ID终止

wait%1 or wait $PID
wait ${!}

等待$ {!}表示“等到最后一个后台进程完成”($!是最后一个后台进程的PID)

睡眠

在指定的时间内添加延迟。

sleep NUMBER[SUFFIX]
sleep 5 (sleep five seconds)

答案 4 :(得分:12)

试试这个:

sleep 10 &
wait %1