On Mon, Nov 25, 2002 at 11:23:55AM -0600, Chris Dillon wrote: > On Sun, 24 Nov 2002, Lee Nelson wrote: > > > myprogram.pl reads a few parameters from STDIN, and then > > forks to work in the background: > > > > my $pid = fork; > > exit if $pid; > > die ("$pn couldn't fork $!\n") unless defined $pid; > > POSIX::setsid() > > or die ("$pn can't start a new session: $!\n"); > > > > Any clues or suggestions welcome. > > The following method to daemonize a PERL process works for me in > FreeBSD (I don't remember why I fork && exit twice, so don't ask): > > require 'sys/syscall.ph'; > > fork && exit; > syscall(&SYS_setsid) || die "Can't call setsid(): $!"; > chdir("/"); > open(STDIN, "</dev/null") || die "Can't redirect stdin: $!"; > open(STDOUT, ">/dev/null") || die "Can't redirect stdout: $!"; > open(STDERR, ">/dev/null") || die "Can't redirect stderr: $!"; > fork && exit; >
The 'double fork' trick ensures that the daemon process gets re-parented as a child of init(8). As init will reap any child process that happens to die, this suppresses zombies plus it has several other effects like dissociating the daemon process from a controlling terminal. Calling setsid(2) has a similar effect, so you probably don't need to fork twice and call setsid(2). The source to the daemon(3) function in /usr/src/lib/libc/gen/daemon.c is a good example of the canonical way to do that sort of thing. Cheers, Matthew -- Dr Matthew J Seaman MA, D.Phil. 26 The Paddocks Savill Way Marlow Tel: +44 1628 476614 Bucks., SL7 1TH UK To Unsubscribe: send mail to [EMAIL PROTECTED] with "unsubscribe freebsd-questions" in the body of the message