return to first page linux journal archive
keywordscontents

#!/usr/bin/perl5.003
#
#  Listing 2.
#
#  Code to illustrate asynchronous communication.
#
require 5.002;
use strict;
use Socket;
use Fcntl;

my $livesocket = 0;

# IO signal handler
sub getsock {
    $livesocket = 1;
}

$SIG{IO} = \&getsock;

my( $proto, $port, $F_SETOWN, $FASYNC );

$port = 6789;
$proto = getprotobyname( 'tcp' );

# Create an Internet protocol socket.
socket( S, AF_INET, SOCK_STREAM, $proto )   or  die "socket:$!";

bind( S, sockaddr_in( $port, INADDR_ANY) );

listen( S, 5 );

#
# Use fcntl to set up the program to accept IO signal when the
# events occur on the socket.
#
$F_SETOWN = 8;
$FASYNC = 020000;
fcntl( S, $F_SETOWN, $$ );
fcntl( S, &F_SETFL, $FASYNC );

while( 1 ){
   
   if($livesocket) {
       print "Signal fired\n";
       accept NS, S;
       select(NS); $| = 1; select(STDOUT);
       print NS "Some message\n";
       $livesocket = 0;
       close NS;
   }

   # do some stuff ...
}

exit;