Operating System - HP-UX
1834149 Members
4002 Online
110064 Solutions
New Discussion

Perl socket-daemon example

 
SOLVED
Go to solution
Stanimir
Trusted Contributor

Perl socket-daemon example

Hi!
I'm trying to make a small client-server /using INET-socket/ example on Perl.
Here it is:
#=======================
# Server
#=======================
use IO::Socket;
my $sock = new IO::Socket::INET (

LocalAddr => 'servername.com',
LocalPort => '7777',
Proto => 'tcp',
Listen => 1,
Reuse => 1,
);
die "Could not create socket: $!\n" unless $sock;
my $new_sock = $sock->accept();
while(defined($Line = <$new_sock>)) {
print $Line;
}
close($sock);

#=============================================# Client
#=============================================
use IO::Socket;
my $sock = new IO::Socket::INET (
PeerAddr => 'servername.com',
PeerPort => '7777',
Proto => 'tcp',
);
die "Could not create socket: $!\n" unless $sock;
print $sock "Hi there!\n";
$sock->send("Hi again!\n");
close($sock);

It is working! Now I want to do the following:

1. To make this server to work like a daemon.
I've tried with:

use Proc::Daemon;
Proc::Daemon::Init();

This was working like daemon , but was damaging socket-part.

2. To make this server to "fork" child process,which will execute row
"print $Line" itself and died after that.
Main proccess must remain live after this
action.

Is anywhere a suitable modules and simple code for doing this?
Thank's in advance!A points-gift will be done! Stan
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Perl socket-daemon example

Here's a close example of something I did for a SysAdmin article to setup multi-platform semaphores using Perl sockets.

The essential steps to daemonizing a process are:
1) fork() -- parent generally just exits the child does the work.
2) setsid() - detaches controlling terminal
3) chdir("/") - so that no filesystems are busy; you don't want to make it difficult for admins to umount a filesystem.
4) setup the signal handlers (e.g. ignore SIGINT, SIGHUP, possibly put in a handler to shutdown when SIGTERM is received.

All of this is illustrated in the attachment plus setting up bidirectional sockets.

The is server.pl.
If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor

Re: Perl socket-daemon example

Here's the client piece that talks to the server using sockets.

This is client.pl.
If it ain't broke, I can fix that.
Stanimir
Trusted Contributor

Re: Perl socket-daemon example

Thanks, Mr. Stephenson!
I must look over your scripts in details.
It seems you are an experienced developer
on Perl. I thing I know the main principles, used in "daemonization" of program. And I
have seen it in module: Daemon.pm.
But when I'm trying to apply this
module /look at my 1. above/, I'm doing
my program to work like daemon, but
the server is stopping to receive messages
for client. May I ask you kindly to
look over this module? What is the problem?
I'm attaching it.
Thank you very much, Stan