evergreen has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I have a need for multiple producer processes to send small messages to a single consumer process all living on the same server - these do not have to be received in order or be guaranteed. Based on reading about socket domains and types, I decided to use AF_UNIX domain and datagram type.

Patching together what I could glean from perldoc and the perl cookbook, here is my code for server and client further below.

The problem is the server starts up and seems to wait at $sock->recv() as expected, but as soon as I run the client, the server comes out of the while loop without printing the data that was received and exits. I would have expected a server output of "Hello" and for the server to continue to listen. Also, nothing is printed for $@ or $! in either server or client

This has been driving me crazy for some hours now. Any help would be appreciated. Thanks!

Server:
#!/usr/bin/perl $| = 1; use strict; use IO::Socket::UNIX; my $SOCK_PATH = "/tmp/mysock"; unlink $SOCK_PATH; my $sock = IO::Socket::UNIX->new( Type => SOCK_DGRAM(), Local => $SOCK_PATH, Listen => 10, ) or die "error: $@"; my $data; while ($sock->recv($data, 1024)) { print "received: $data\n"; } print "exiting: $!\n";
Client
#!/usr/bin/perl $| = 1; use strict; use IO::Socket::UNIX; my $SOCK_PATH = "/tmp/mysock"; my $sock = IO::Socket::UNIX->new( Type => SOCK_DGRAM(), Peer => $SOCK_PATH, ); $sock->send("Hello") or die "error: $@";

Replies are listed 'Best First'.
Re: Unix socket domain datagram within local server
by haukex (Archbishop) on Dec 22, 2018 at 07:53 UTC

    From the documentation of recv:

    Returns the address of the sender if SOCKET's protocol supports this; returns an empty string otherwise. If there's an error, returns the undefined value.

    This means the while loop will terminate when the call happens to return a false value. This works for me:

    while (1) { defined $sock->recv($data, 1024) or die "recv error: $!"; ...

    Update 2019-08-17: Updated the link to "Truth and Falsehood".

      Thanks, that fixed it.
Re: Unix socket domain datagram within local server
by tybalt89 (Monsignor) on Dec 22, 2018 at 07:57 UTC
    #!/usr/bin/perl # https://perlmonks.org/?node_id=1227597 use strict; use warnings; $| = 1; use IO::Socket::UNIX; my $SOCK_PATH = "/tmp/mysock"; unlink $SOCK_PATH; my $sock = IO::Socket::UNIX->new ( Type => SOCK_DGRAM(), Local => $SOCK_PATH, Listen => 10, ) or die "error: $@"; my $data; while ( defined $sock->recv($data, 1024) ) { print "received: $data\n"; } print "exiting: $!\n";