I typically use a variation of this 'daemonize' code taken from perlipc. This sets up the script's environment and disassociates it from the caller entirely.
sub daemonize {
chdir '/' or die "Can't chdir to /: $!";
open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
open STDOUT, '>/dev/null'
or die "Can't write to /dev/nul
+l: $!";
defined(my $pid = fork) or die "Can't fork: $!";
exit if $pid;
setsid or die "Can't start a new session: $!";
open STDERR, '>&STDOUT' or die "Can't dup stdout: $!";
}
You have to setsid too, to disassociate from your parent's process group:
#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw(setsid);
# Become a daemon
my $pid=fork;
exit if $pid; # Parent exits here
die "Couldn't fork $!" unless defined($pid);
die "Couldn't start new session $!" unless POSIX::setsid();
# Do your daemon bit...