1
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.

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

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

However, the error occured

not a pid or valid job spec

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

Thanks a lot.

1
  • I think the asynchronous command execution is pointless here! Here a sub-process started in the background and then immediately waited to finish, so instead of the lot of code use simply fpfunction to start a sub-process and wait for it. If You want to limit the number of process started I suggest to use make. Commented Jul 17, 2013 at 10:29

1 Answer 1

5

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

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 wait from the shell, you would normally leave off the parentheses.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.