Bourne sh/subshell question

Conor P. Cahill cpcahil at virtech.uucp
Mon Nov 20 09:16:16 AEST 1989


In article <1989Nov17.105828.2894 at dlcq15.datlog.co.uk>, scm at dlcq15.datlog.co.uk (Steve Mawer) writes:
> (
>     echo subshell - $$
>     sleep 10
> ) &
> echo shell - $!
> 
> When run, it produces the following output:
> 
> $ sh script
> subshell - 25654
> shell - 25655
> $
> 
> My question is twofold, firstly why aren't the two PIDs identical,
> and secondly, as they're not, why is the PID of the last background
> process 1 greater than the current process PID of the subshell?

The reason for the discrepancy is that the $$ and $! are interpreted by
the parent shell (25654).  the $! (25655) is the actual process id of the
sub-shell.

Apparently the entire subshell script is processed by the shell prior to
passing it to the sub-shell.

Changing the subshell to 
	(
	    echo subshell - \$$
	    sleep 10
	) &

gets you "subshell - $$"

Using
	(
	    eval echo subshell - \$$
	    sleep 10
	) &

gets the original output.

If you need to have the correct $$ evaluation you could do something like
the following:

	sh <<\endsh &
	    echo subshell - $$
	    sleep 10
	endsh

	echo subshell = $!
	echo shell    = $$

Good luck.

-- 
+-----------------------------------------------------------------------+
| Conor P. Cahill     uunet!virtech!cpcahil      	703-430-9247	!
| Virtual Technologies Inc.,    P. O. Box 876,   Sterling, VA 22170     |
+-----------------------------------------------------------------------+



More information about the Comp.unix.questions mailing list