To elaborate on: See the following: - stackoverflow.com/questions/9119885/…
See particularly the following quote from Chris Dodd:
Unfortunately there's no easy way to do this prior to bash version 4, when $BASHPID was
introduced. One thing you can do is to write a tiny program that prints its parent PID:...
If you have bash 4 and BASHPID, see $$ in a script vs $$ in a subshell
I don't have version 4, so I can't provide an example of it's usage.
Or write a tiny C program which execvs it's arguments and make it setuid to USER
.
Or even make a setuid shell script (not generally recommended). Hopefully the USER
is fixed; if not, get the source for runuser
, this is essentially what runuser (not a POSIX command) does.
PID=`su - $USER -c "$SCRIPT > /dev/null 2>&1 & echo $!"`
The problems with the your use of su
(above) include:
- the
$!
is being executed in the context of the -c
sub-shell of su
, not the current shell where PID
is,
- you're requesting that your
SCRIPT
be run as a login shell, so you don't even know if USER
's shell supports $!
,
- you have no control over the parent-child process chain that
su
(and the user's shell) create.
IOW, when you use
PID=`$SCRIPT > /dev/null 2>&1 & echo $!`
there's only one program involved, bash
, and two (maybe three?) processes that you pretty much have complete control over. When you throw su
into the mix, that changes things much more than is apparent on the surface -- bash
and su
support similar arguments, right?!?
For obvious reasons, su
does mucho magic to protect it and its' children's environment from attacks; it doesn't even like being put in the background....