≡ Menu

Write a Daemon in Perl

The code below is a template for a daemon written in Perl. Use the code below as a starting point when you have to write a program that has to persist in the background to do its things and without a gui.

use POSIX qw(setsid);

chdir '/' or die "Can't chdir to /: $!";
umask 0;
open STDIN, '/dev/null'
    or die "Can't read /dev/null: $!";

#open STDOUT, '>/dev/null'
#    or die "Can't write to /dev/null: $!";

open STDERR, '>/dev/null'
    or die "Can't write to /dev/null: $!";

defined(my $pid = fork)
    or die "Can't fork: $!";

exit if $pid;

setsid or die "Can't start a new session: $!";

while(1) {
    print "Hello...n";

Note that one of the lines above is commented out to let the output print to the screen. Uncomment this in the final code to silence your program. For more on this code, see this tutorial: http://www.webreference.com/perl/tutorial/9/.

{ 0 comments… add one }

Leave a Comment