in reply to Problems with forking

Update: You do realize you are never incrementing $i in the while loop, making it an infinite while loop? And maybe the writes to the file are being buffered so you do not see anything right away. How long have you left it running?

Here is a short subroutine I like to use that is based on what Stein (CGI.pm) recommends in "Network Programming with Perl". As you can see, there are several additional things you should be doing for your script to be a proper daemon. I have seen forking multiple times before, but I do not think that is actually necessary. It's probably a more expensive, less elegant way to e.g. help disassociate from the shell. Though if you want to you could also call daemonize() more than once.

use IO::Socket; use POSIX qw(WNOHANG setsid); sub daemonize { $SIG{CHLD} = 'IGNORE'; # Configure to autoreap zombies die "Can't fork" unless defined ( my $child = fork ); # FORK +<<<<<<<<<<<< CORE::exit(0) if $child; # Parent exits setsid(); # Become session leader open( STDIN, "</dev/null" ); # Detach STDIN from shell open( STDOUT, ">/dev/null" ); # Detach STDOUT from shell open( STDERR, ">&STDOUT" ); # Detach STDERR from shell chdir '/tmp'; # Change working directory umask(0); # Reset umask $ENV{PATH} = '/bin:/sbin:/usr/sbin'; # Reset PATH }
See also Re: Persistent perl.

Elda Taluta; Sarks Sark; Ark Arks

Replies are listed 'Best First'.
Re^2: Problems with forking
by mraspberry (Initiate) on Apr 02, 2011 at 13:18 UTC

    Thanks, wow I'm dumb, I wrote that test very fast and apparently was more tired than I thought I was. Can't believe I missed the fact that I wasn't incrementing that counter. I like the suggestion on the proper way to daemonize. Thanks for the help.