Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Non-Blocking Bidirectional Communication using Unix Sockets

by dooberwah (Pilgrim)
on Jun 05, 2002 at 19:16 UTC ( #171962=snippet: print w/ replies, xml ) Need Help??

Description: The parent pid sends a string to the child pid, which the child prints out. The child then sleeps for 2 seconds before sending a string to the parent. Instead of locking up completaly the parent prints "Waiting...\n" until there is input for it to read.

I wrote this to encorperate it into a larger Tk script which I don't want freezing when it forks off to download information.

NOTE: This does not work on Windows (hence the name "Unix Sockets")!

The code is a based on of "pipe2" from perlipc. See also: IO::Socket, IO::Select, and perlipc.

#!/usr/bin/perl -w 

use strict;
use Socket;
use IO::Socket;
use IO::Select;

socketpair(CHILD, PARENT, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
    or die "socketpair: $!";
    
CHILD->autoflush(1);
PARENT->autoflush(1);

my $pid;
my $s = IO::Select->new();
$s->add(\*CHILD);


if ( $pid = fork ) {
    close PARENT;
    print CHILD "Parent Pid $$ is sending this\n";
    #chomp(my $line = <CHILD>);
    my $line;
    while ( 1 ) {
        if ( $s->can_read(0) ) {
            foreach my $handle ( $s->can_read(0) ) {
                recv($handle, $line, 1024, 0);
            }
            last;
        }
        print "Waiting...\n";
    }
    chomp $line;
    print "Parent Pid $$ just read this: '$line'\n";
    close CHILD;
    waitpid($pid, 0);
} else {
    die "cannot fork: $!" unless defined $pid;
    close CHILD;
    chomp(my $line = <PARENT>);
    print "Child Pid $$ just read this: '$line'\n";
    sleep 2;
    print PARENT "Child Pid $$ is sending this\n";
    close PARENT;
    exit;
}
Comment on Non-Blocking Bidirectional Communication using Unix Sockets
Download Code
Replies are listed 'Best First'.
Re: Non-Blocking Bidirectional Communication using Unix Sockets
by Anonymous Monk on Feb 09, 2015 at 20:57 UTC
    You keep using that word "non-blocking."
    I do not think it means what you think it means.

    perldoc -f sysread
    perldoc -f syswrite

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://171962]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2015-07-29 01:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (260 votes), past polls