FuguLib::Daemon(3p) Perl Library Manual FuguLib::Daemon(3p)

FuguLib::Daemondetach a Perl program from its controlling terminal

use FuguLib::Daemon;

FuguLib::Daemon->daemonize(
    logfile => '/var/log/mydaemon.log',
    on_fork => sub ($pid) { $state->write_pid($pid) },
);

FuguLib::Daemon turns the running program into a daemon: it forks, the parent exits, and the child becomes a session leader with its standard descriptors redirected away from the terminal.

The module keeps no state and has a single class method.

(%args) forks into the background and detaches from the controlling terminal.

The parent calls on_fork if one was given, then exits with status 0; () therefore returns only in the child. The child calls setsid(2), reopens standard input from /dev/null, appends standard output to logfile, and duplicates standard output onto standard error.

The arguments are as follows:

logfile
Path for standard output and standard error. The default is /dev/null, which is what a daemon logging through FuguLib::Log(3p) in syslog mode wants. The file is opened for appending.
on_fork
Code reference called in the parent with the child's process ID before the parent exits. This is where a PID file is written, because only the parent knows the child's process ID at that point.

daemonize() returns nothing in the child and never returns in the parent.

Daemonize, writing a PID file from the parent and logging through syslog:

my $log = FuguLib::Log->new(mode => 'syslog', ident => 'mydaemon');
my $state = FuguLib::State->new('/var/run/mydaemon.pid');

FuguLib::Daemon->daemonize(
    on_fork => sub ($pid) { $state->write_pid($pid) },
);

$log->info('started, pid %d', $$);

daemonize() dies rather than returning if the fork fails, if setsid(2) fails, or if any of the three standard descriptors cannot be redirected. These are start-up conditions a daemon cannot recover from.

setsid(2), daemon(3), FuguLib::Log(3p), FuguLib::Privdrop(3p), FuguLib::Process(3p), FuguLib::State(3p)

Dick Olsson <hi@senzilla.io>

Call daemonize() before opening files or sockets that the daemon expects to keep: the standard descriptors are redirected in the child, but anything already open is inherited as it is.

The parent exits with status 0 even if on_fork fails. A caller that must know whether the PID file was written has to check for it separately.

July 27, 2026 OpenBSD