If i have a file called myprogram containing

sleep 200

Run this in the background:

$ sh myprogram &

i want to know when myprogram has completed by using wait command

$ cat >notify
wait PID
echo "Program completed"
$ sh notify &

PID is the process ID given from third command, my problem is that the message "program completed" printed on the terminal immediately after the last command,why wait does not wait? , i am using ubuntu 11.10

  • 2
    I'm pretty sure wait can only wait for child processes, which means it must be run in the parent shell, not a separate one like you are doing with the sh wait. – jw013 Aug 16 '12 at 15:59

The child-parent relationship gets ruined by all the '&' involved.

The wait(2) system call, which the wait builtin is apparently based on, will only work for a direct child PID of the process that calls wait(2).

When you invoke sh myprogram &, you run sh as a child of the interactive shell.

When you invoke sh notify &, that sh is a child of the interactive shell.

So the second sh has no direct parent relationship with the first sh, and wait will not work.

This won't even work if you invoke sh myprogram &; sh notify; either, because the wait command is invoked by a child of the interactive shell.

What does work for me is this: sh myprogram &; wait The wait command causes the interactive shell (parent of the sh invoked explicitly) to hang around until the sh exits.


In this specific example, it's best to just run wait in the main shell as Bruce's answer shows, but if you had some alternate situation where you can't do that - for example, if you need to run myprogram as a foreground process, or if it's a daemon without a controlling terminal - you can use a program I've written called pwait that will wait for an arbitrary process to finish. To use it in this example, after running

$ sh myprogram

you would obtain the process ID of myprogram somehow, and then in notify, instead of wait you'd use

pwait PID

My version of pwait is Linux-only, for now. If you're running FreeBSD, they have their own implementation which appears to be available as a standard utility. You can also sort of fudge it using ps to repeatedly check whether the command has finished, as in this shell script (although that doesn't tell you the command's exit code, in case that's relevant).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.