[Cialug] Starting two jobs at once

Zachary Kotlarek zach at kotlarek.com
Tue Nov 27 21:23:17 CST 2012


On Nov 27, 2012, at 2:45 PM, Matthew Nuzum <newz at bearfruit.org> wrote:

> 
> On Nov 27, 2012, at 4:41 PM, Matthew Nuzum <newz at bearfruit.org> wrote:
>> Right, I know about fg but then you're stuck with a daemon in the foreground and you need to ctrl+c it as well, right? I just want it to die (gracefully if possible). I can imagine in an upcoming project actually having three tasks, sass, mongodb and a python or js based web server. That means ctrl+c ctrl+c ctrl+c.
>> 
>> Zachary, echo $$ returns the PID of the last process started? I tried googling it but didn't get anything remotely helpful. :-)


$$ is the PID of the current bash process. You can also use $BASHID in bash (but not `sh` or `dash`), and you can use $PPID to get the parent's PID.

$! is the PID of the last process backgrounded by the shell process controls like & or `bg`. It is not set by programs that run in the foreground, or that detach themselves without intervention from the shell. Given your example below this may be easier to use.


> launch-bg-process &
> p1pid=`echo $$`
> launch-fg-process
> kill $p1pid
> echo Have a nice day!



Mostly, with two exceptions. First, these PID variables are local to the current shell, so you don't want to launch subshells/backticks/etc. In your example it will work because $$ will be evaluated before `echo` is launched, but it's much safer and more efficient to use:
	p1pid=$$

Second, for this usage you mean $! not $$, as you want the PID of the background'ed process, not of the shell itself:
	p1pid=$!
or since you're only launching a single process in the background, you can simply end with:
	kill $!
as $! is not affected by the foreground process launched in the middle.

If you want to be able to handle abnormal exits/SIGINT/SIGTERM/etc. you'll need to be sure shell execution continues as you expect when the foreground process exits (at least be sure you aren't running with `set -e`) and/or install a handler for the situations. Some quick testing is probably the easiest way to determine if this is a concern for your usage.

	Zach

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2746 bytes
Desc: not available
URL: <http://cialug.org/pipermail/cialug/attachments/20121127/e34b78ad/attachment.bin>


More information about the Cialug mailing list