Håkon Hægland Håkon Hægland - 3 months ago 9
Perl Question

How to create a Unix Domain socket?

I am trying to learn how to use sockets to communicate between processes on the same machine. I started with this simple test program taken from Perl Cookbook:

use feature qw(say);
use strict;
use warnings;
use IO::Socket;

my $socket_file = 'mysocket';
if ( -e $socket_file ) {
unlink $socket_file or die "Could not delete socket file '$socket_file': $!";
}
my $sock = IO::Socket::UNIX->new(
LocalAddr => $socket_file,
Type => SOCK_STREAM,
Listen => 5, # listen to max 5 connections
) or die "Could not create socket: '$@'";

say "Created socket successfully..";
sleep 1;
close $sock;
say "Closed socket..";

exit;


The output is:

Could not create socket: '' at ./test.pl line 10.


So the question is: Why does
IO::Socket::UNIX->new()
fail, and why does it not set
$@
when it fails?

mob mob
Answer

It doesn't set $@ because IO::Socket::UNIX doesn't use eval anywhere. If you print out $! instead of $@, you might see:

Invalid argument at xxx.pl line 10.

At which point you may consult the IO::Socket::UNIX docs and see that the correct parameter to pass is Local and not LocalAddr.