bash shell脚本中的wait命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17690180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:56:27  来源:igfitidea点击:

wait command in shell script

bash

提问by Sam

fork(){
    i=0
    count=0
    while (($count<5))
    do
        fpfunction &
        pid=$!

        #Ensure the pid is available 
        if [  -z "$pid" ]; then
        echo "IS NULL"
        else
        Array[$i]=$pid
        echo "PID is $pid"
        fi

        wait [$pid]
        i=$((i+1))
        count=$(( count+1 ))
    done

    echo "PID: ${Array[*]}"

}

The fpfunction() only echo a string, so I dont write it here.

fpfunction() 只回显一个字符串,所以我不写在这里。

My understanding to wait() is it will wait a child process to complete and then return a value.

我对 wait() 的理解是它会等待子进程完成然后返回一个值。

I put wait() in my script because I want to ensure all child processes are finished.

我将 wait() 放在我的脚本中,因为我想确保所有子进程都已完成。

However, the error occured

然而,错误发生了

not a pid or valid job spec

不是 pid 或有效的工作规范

Is my understanding wrong? please let me know how to fix this issue.

我的理解有误吗?请让我知道如何解决这个问题。

Thanks a lot.

非常感谢。

回答by paxdiablo

If the process ID is, for example, 42 then your waitinstruction becomes:

例如,如果进程 ID 是 42,那么您的wait指令将变为:

wait [42]

which is not what you want - the square brackets are a problem. It should be:

这不是您想要的 - 方括号是一个问题。它应该是:

wait $pid

as per the following transcript:

根据以下成绩单:

pax> date ; sleep 60 &
Wednesday 17 July  10:43:51 WST 2013
[1] 5200

pax> pid=$! ; echo $pid
5200

pax> wait [$pid]
bash: wait: '[5200]': not a pid or valid job spec

pax> wait $pid ; date
[1]+ Done sleep 60
Wednesday 17 July  10:44:51 WST 2013


And, just as an aside (irrelevant to the answer), wait()is better suited to the C wait()function.If you're using waitfrom the shell,you would normally leave off the parentheses.

而且,顺便说一句(与答案无关),wait()更适合 Cwait()函数。如果您waitshell使用通常会省略括号。