[comp.unix.wizards] newmail also displays on console

cudcv@warwick.ac.uk (Rob McMahon) (03/18/89)

I'm cross-posting this to comp.unix.wizards, and sending follow-ups there,
since this has stopped being an elm question.  I'll report back here if no-one
else does.

In article <91@dsinc.UUCP> syd@dsinc.UUCP (Syd Weinstein) writes:
>In article <330@wubios.wustl.edu> david@wubios.UUCP (David J. Camp) writes:
>:I have studied the code in newmail.c, and I do not see how the process put
>:in the background is automatically killed upon logout.  Perhaps someone
>:in-the-know can explain to me how this is done.
>
>It's really very simple.  We do nothing, and when the init process sends a
>SIGHUP, we take the default action, to die.

[But processes not in the process group of the terminal on systems with job
control never see the SIGHUP]

This is quite an interesting problem really.  If the background process does
not fork, it can check getppid() occasionally, when it returns 1 it knows it
has been orphaned and can exit.  If it does fork things gets more tricky.  It
can try to kill(shell_pid, 0), but a) not all systems allow this, and b)
there's a chance of pid reuse.  The BSD `leave' program uses getlogin() and
compares it against a stashed copy.  At least this means that the only person
it's going to annoy is yourself.

Anyone got any better ideas on how a process which forks and carries on
running in the background can detect when the original shell has gone away ?

Rob
-- 
UUCP:   ...!mcvax!ukc!warwick!cudcv	PHONE:  +44 203 523037
JANET:  cudcv@uk.ac.warwick             ARPA:   cudcv@warwick.ac.uk
Rob McMahon, Computing Services, Warwick University, Coventry CV4 7AL, England

tanner@cdis-1.uucp (Dr. T. Andrews) (03/23/89)

In article <123@titania.warwick.ac.uk>, cudcv@warwick.ac.uk (Rob McMahon) writes:
) Anyone got any better ideas on how a process which forks and carries
) on running in the background can detect [death of original shell]

Sure, here's how to do it.  Define AUTO_BACKGROUND and don't run the
prog with an '&'.

Before the fork() call, get the parent process ID (getppid(2) should
do this).  Make sure it's not something silly like 0 or 1, and save it.
Do the fork(2), and the kid still remembers the parent process id.

Then, condition your work loop on (kill(shell_pid, 0) == 0) and you
are in business.  As soon as that kill() fails, you clean up if
needed, and die politely (and silently!)

This also works OK if you get SIGHUP'ed to death.
-- 
...!bikini.cis.ufl.edu!ki4pv!cdis-1!tanner  ...!bpa!cdin-1!cdis-1!tanner
or...  {allegra killer gatech!uflorida decvax!ucf-cs}!ki4pv!cdis-1!tanner