Michael C. Toren on 6 Jan 2004 03:01: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:55:14PM -0500, Stephen Gran wrote:
> So checking $PPID from within a script works, but appears to return 1
> when run from the console.

Which is what you'd expect -- your console shell's parent is init.

> 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.

You're close, but a little off; the key is that when one program execs
another, the PID and PPID stay the same.

The way init is normally configured, it forks off a child process, waits
for the child to die, and repeats.  The child execs getty, but getty
retains it's PID and PPID of init.  getty prompts the user for a username,
then execs login, but login retains it's PID and PPID of init.  login
prompts the user for a password, and if valid execs the user's shell, but
retains it's PID and PPID of init.  So, it's perfectly conceivable that
$PPID will return 1 from your console login shell.

(There's a little white lie in the above paragraph -- login does a few
forks in order to perform some PAM cleanup routines as root -- but it's
close enough to the truth for the purposes of this conversation.)

> 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.

I don't see how testing to see if your parent process is init will give
you any insight into weather or not your script is being executed at boot
time or not, unfortunately.  What if a user types "exec
/etc/init.d/whatever" from a console login shell?

-mct
___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug