Well - it's better if you could state what this daemon is supposed to do. As there are specialized frameworks/libraries for various tasks.
For simplest daemon that does nothing, just exists, you can easily do this:
#!/usr/bin/perl
use strict;
use warnings;
use Carp;
use POSIX qw( setsid );
daemonize();
do_your_daemon_stuff();
exit;
sub daemonize {
chdir '/' or croak "Can't chdir to /: $!";
open STDIN, '/dev/null' or croak "Can't read /dev/null: $!";
open STDOUT, '>/dev/null' or croak "Can't write to /dev/null: $!";
defined(my $pid = fork) or croak "Can't fork: $!";
exit if $pid;
setsid or croak "Can't start a new session: $!";
open STDERR, '>&STDOUT' or croak "Can't dup stdout: $!";
}
sub daemonize() was liften from perldoc perlipc (with minor change).
That's all - the code now properly daemonizes, and can do anything you want.
I just read your edit, that you want TCP server.
OK. Here is simplistic code:
#!/usr/bin/perl
use strict;
use warnings;
use Carp;
use POSIX qw( setsid );
use IO::Socket;
my $server_port = get_server_port();
daemonize();
handle_connections( $server_port );
exit;
sub daemonize {
chdir '/' or croak "Can't chdir to /: $!";
open STDIN, '/dev/null' or croak "Can't read /dev/null: $!";
open STDOUT, '>/dev/null' or croak "Can't write to /dev/null: $!";
defined(my $pid = fork) or croak "Can't fork: $!";
exit if $pid;
setsid or croak "Can't start a new session: $!";
open STDERR, '>&STDOUT' or croak "Can't dup stdout: $!";
}
sub get_server_port {
my $server = IO::Socket::INET->new(
'Proto' => 'tcp',
'LocalPort' => 31236,
'Listen' => SOMAXCONN,
'Reuse' => 1,
);
die "can't setup server" unless $server;
return $server;
}
sub handle_connections {
my $port = shift;
my $handled = 0;
while ( my $client = $port->accept() ) {
$handled++;
print $client "Hi, you're client #$handled\n";
chomp ( my $input = <$client> );
my $output = reverse $input;
print $client $output, "\n";
print $client "Bye, bye.\n";
close $client;
}
return;
}
Just remember that this is blocking tcp server, so it will be able to handle 1 connection at the time. If you want more than 1 - it becomes more complex, and you have to ask yourself if you prefer multithreading (or multi-processing), or you prefer single-process, event based server.