On Tue, Aug 24, 2004 at 03:59:57PM -0500, Errin Larsen wrote:
> As I understand what's going on, the Process (let's say PID=100)
> spawns a child with the fork() function (let's say PID=200). This
> (200) is assigned to $pid in the parent, and zero (0) is assigned to
> $pid in the child. So, what does "my $pid=fork()" resolve to in each
> case? I'll assume that it resolves to the PID that fork returns. So,
> in the parent, the statement resolves to 200 and the unless statement
> doesn't resolve. In the child, the statement resolves to 0 and the
> unless statement DOES resolve. So, the parent prints a message to
> STDOUT and quits, while the child keeps on running (in the little
> do/while loop) doing that stuff that's in there :)
That sounds about right. At the fork() call the program spawns into two
processes; the child gets 0 back from fork() (if it wants to know its own
pid, it can just look at $$) and the parent gets the child's pid back (in
case it wants to send signals to the child). You'll notice a lot of
daemons store the child pid in /var/run, e.g., apache.pid, so when you
call the daemon script later it can send the proper signal to the
now-detached child.
Usually, you'll want to implement custom signal handling in the child
(i.e., local $SIG{HUP} = \&SomeCode).
> Ok ... so, um, why go through all this? Why not just write your
> do/while block and just execute it in the background on the command
> line? is fork() doing something else that helps a daemon that I'm not
> aware of?
I guess primarily because you don't want your user to have to background
the task. If you're writing a daemon script thats going to go in
/etc/init.d, it has to detach itself--the initscripts aren't going to
put it in the background for you.
If you background a task from the shell, then the shell will be its
parent. If you detach a daemon like my code sample below, the parent
dies and the child is adopted by init (pid 1). I can't think off the top
of my head why this is important, but it is a difference.
I think just as a matter of good programming style, if your program is
always suppose to background itself, you should have the program
background itself, rather than relying on the user to background it.
> On Sat, 21 Aug 2004 09:53:23 -0400, Adam Rosi-Kessel
> > Here's the skeleton of it:
> >
> > ----
> > unless (my $pid = fork()) {
> > do {
> > &SendEmailToUsers;
> > sleep 3 * 24 * 60 * 60;
> > } while (1);
> > }
> >
> > print "Starting email daemon...\n";
--
Adam Rosi-Kessel
http://adam.rosi-kessel.org
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>