I trie to make a Perlscript where only one instance is running, and the next call of the script sends the payload to the queue of the first one. If the queue is done the script should terminate. I tried this with sockets - they should be blocking... I use Win7
If I call this script with test1 and test2 in two different command windows booth tell me they open the port and the queue echo back but don't terminate.
use 5.14.2;
use strict;
use warnings;
#Filename: singleInstance.pl
use Socket;
use threads;
use Thread::Queue;
sub sendToPort($);
my $q = Thread::Queue->new(); # A new empty queue
# Worker thread
my $thr = threads->create(
sub {
# Thread will loop until no more work
while (defined(my $item = $q->dequeue())) {
say $item;
sleep 10;
}
die "all done";
}
);
my $string = shift;
my $proto = getprotobyname('tcp');
my $port = 7890;
my $server = "localhost";
socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
or die "Can't open socket $!\n";
setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1)
or die "Can't set socket option to SO_REUSEADDR $!\n";
bind( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
or die sendToPort($string);
listen(SOCKET, 5) or die "listen: $!";
print "SERVER started on port $port\n";
$q->enqueue($string);
# accepting a connection
my $client_addr;
while ($client_addr = accept(NEW_SOCKET, SOCKET)) {
# send them a message, close connection
my $string = <NEW_SOCKET>;
$q->enqueue($string);
close NEW_SOCKET;
}
sub sendToPort($){
# create the socket, connect to the port
socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2])
or die "Can't create a socket $!\n";
connect( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
or die "Can't connect to port $port! \n";
print SOCKET $string;
close SOCKET or die "close: $!";
die "send to open script";
}