views:

73

answers:

1

My question is very similar to this one except that my background process was started from a script. I could be doing something wrong but when I try this simple example:

#!/bin/bash
set -mb  # enable job control and notification
sleep 5  &

I never receive notification when the sleep background command finishes. However, if I execute the same directly in the terminal,

$ set -mb  
$ sleep 5  &
$
[1]+  Done                    sleep 5

I see the output that I expect.

I'm using bash on cygwin. I'm guessing that it might have something to do with where the output is directed, but trying various output redirection, I'm not getting any closer.

EDIT: So I have more information about the why (thx to jkramer), but still looking for the how. How do I get "push" notification that a background process started from a script has terminated? Saving a PID to a file and polling is not what I'm looking for.

A: 

The job control of your shell only affects processes controlled by your terminal, that is tasks started directly from the shell.

When the parent process (your script) dies, the init process automatically becomes the parent of the child process (your sleep command), effectively killing all output. Try this example:

[jkramer/sgi5k:~]# cat foo.sh
#!/bin/bash

sleep 20 &
echo $!
[jkramer/sgi5k:~]# bash foo.sh 
19638
[jkramer/sgi5k:~]# ps -ef | grep 19638
jkramer  19638     1  0 23:08 pts/3    00:00:00 sleep 20
jkramer  19643 19500  0 23:08 pts/3    00:00:00 grep 19638

As you can see, the parent process of sleep after the script terminates is 1, the init process. If you need to get notified about the termination of your child process, you can save the content of the $! variable (PID of the last created process) in a file or somewhere and use the `wait´ command to wait for its termination.

jkramer
Thanks, jkramer - very imformative. So I need to do something different, but using the wait command negates the point of sending the child process to the background. I want to call the script (that may optionally background a child process), and then continue to use the same terminal. If it's waiting then the terminal will be unavailable, right? So if I save the PID to reference later, I'd still have to periodically poll to see if it's done while I'm hoping to have the notification pushed to me instead.
Keith Bentrup