如何创建Unix域套接字?

时间:2016-09-07 21:26:32

标签: perl sockets

我正在尝试学习如何使用套接字在同一台机器上的进程之间进行通信。我从这个简单的测试程序开始,这个程序来自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;

输出结果为:

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

所以问题是:为什么IO::Socket::UNIX->new()失败,为什么失败时没有设置$@

1 个答案:

答案 0 :(得分:2)

它没有设置$@,因为IO::Socket::UNIX并未在任何地方使用eval。 如果您打印$!而不是$@,则可能会看到:

Invalid argument at xxx.pl line 10.

此时您可以咨询IO::Socket::UNIX docs并查看要传递的正确参数是Local而不是LocalAddr