Stephen Gran on 5 Jan 2004 23:55:02 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] How to find parent in the shell?


On Mon, Jan 05, 2004 at 06:08:35PM -0500, gabriel rosenkoetter said:
> On Mon, Jan 05, 2004 at 02:53:31PM -0500, Stephen Gran wrote:
> > portable and feed it back to upstream.  Any pointers towards something
> > truly portable would be great.  Again, people with other platforms
> > (hint) are a big help, because I don't have access to them myself.
> 
> Well, getppid(2) seems like the Right way to do this, and various
> shells provide direct access to it's output (it's $PPID in zsh, for
> instance).

This was my feeling, but this is what troubled me with using it:
(logged in on console, tty2)
steve:~$ ps ax | grep bash
 1566 tty2     R      0:00 -bash
 1596 pts/0    S      0:00 -bash
 1612 pts/2    S      0:00 /bin/bash
 1641 pts/3    S      0:00 /bin/bash
 1650 pts/3    S      0:00 /bin/bash
steve:~$ echo $PPID
1
steve:~$ cat > PPID
echo "PPID = $PPID"
steve:~$ sh PPID
PPID = 1566
steve:~$

So checking $PPID from within a script works, but appears to return 1 
when run from the console.  I understand that init launches getty, 
which then launches bash when I log in, but I would have thought that 
the pid of the getty process should have been the value in $PPID.  Maybe 
I misunderstand getty, though (entirely possible), and it is really that
init spawns a getty process to listen for a login, and then itself
launches a shell when you log in.  If this is the case, then my first
feeling, that a simple `if [ "$PPID" = 1 ]; then ...` should be fine.  
I was just worried that it couldn't be that simple because of my
experimenting, and probable misinterpretation of how getty and login
work.  It even seems like $PPID works in dash, so hopefully it's
portable enough.
-- 
 --------------------------------------------------------------------------
|  Stephen Gran                  | There are three things I always forget. |
|  steve@lobefin.net             | Names, faces -- the third I can't       |
|  http://www.lobefin.net/~steve | remember.   -- Italo Svevo              |
 --------------------------------------------------------------------------

Attachment: pgp9pvQ1ozv3f.pgp
Description: PGP signature