前两天介绍了使用Socket及IO::Socket 来进行TCP
client/server的编程基本套路和代码,现在再介绍使用Socket及IO::Socket模块来进行Unix domain
Socket的client/server开发。
因此使用Unix socket来设计单机的IPC应用是首选。非常实用。大量的Unix应用软件都使用unix socket来进行程序间通信。
#!/usr/bin/perl -w
use strict;
use Socket;
use IO::Handle;
my $path = $ARGV[0] || '/tmp/daytime.sock';
socket(my $sock, PF_UNIX, SOCK_STREAM, 0);
my $sun = sockaddr_un($path);
connect($sock, $sun) or die "Connect: $!\n";
$sock->autoflush(1);
my $buf = <$sock>;
my $bs = length($buf);
print "Received $bs bytes, content $buf\n";
close $sock;
#!/usr/bin/perl -w
# tcp_socket_dt_srv.pl
use strict;
use Socket;
use IO::Handle;
use POSIX qw(WNOHANG);
my $path = $ARGV[0] || '/tmp/daytime.sock';
$SIG{'CHLD'} = sub {
while((my $pid = waitpid(-1, WNOHANG)) >0) {
print "Reaped child $pid\n";
}
};
socket(SOCK, PF_UNIX, SOCK_STREAM, 0)
or die "socket() failed: $!";
setsockopt(SOCK,SOL_SOCKET,SO_REUSEADDR,1)
or die "Can't set SO_REUSADDR: $!" ;
unlink $path if -r $path;
bind(SOCK,sockaddr_un($path)) or die "bind() failed: $!";
listen(SOCK,SOMAXCONN) or die "listen() failed: $!";
warn "Starting server on path $path...\n";
while (1) {
next unless my $sockname = accept(SESSION,SOCK);
defined (my $pid=fork) or die "Can't fork: $!\n";
if($pid==0) {
SESSION->autoflush(1);
print SESSION (my $s = localtime);
close SESSION;
exit 0;
}else {
print "Forking child $pid\n";
}
}
close SOCK;
文章评论(0条评论)
登录后参与讨论