[comp.unix.questions] Bourne sh/subshell question

scm@dlcq15.datlog.co.uk (Steve Mawer) (11/17/89)

I have a small problem with the following script:

---------------------SCRIPT STARTS----------
(
    echo subshell - $$
    sleep 10
) &
echo shell - $!
----------------------SCRIPT ENDS-----------

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?

E-mail replies for preference, I'll summarize if there's sufficient
interest.

--
Steve C. Mawer        <scm@datlog.co.uk> or < {backbone}!ukc!datlog!scm >
                       Voice:  +44 1 863 0383 (x2153)

cpcahil@virtech.uucp (Conor P. Cahill) (11/20/89)

In article <1989Nov17.105828.2894@dlcq15.datlog.co.uk>, scm@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     |
+-----------------------------------------------------------------------+