On 05/13/2016 11:30 AM, Unknown User wrote:
I wrote this scrpt to fork off a few child processes, then the child
processes process some data, and send the data back to the parent
through a tcp socket.
This is not working as i expected it would. Why not? How can it be corrected?
there are many issues here. first off, please indent and format your code. it
is impossible to read and i missed the outer for loop the first time i scanned
it.
#!/usr/bin/perl -w
use strict;
use IO::Socket::INET;
print $$,"\n";
for my $num (1 .. 100) {
print "Working on: $num \n";
my $pid = fork;
you are forking 100 times.
if ($pid > 0) {
# Parent
my $listen = IO::Socket::INET->new(
LocalAddr => "127.0.0.1",
LocalPort => "8989",
Listen => 1024,
ReuseAddr => 1,
Proto => 'tcp',
) or
and listening 100 times. that is the cause of the socket in use error.
you should put the parent socket code before the 100 loop and listen in
one place. but then you won't be able to handle all the children. you
could fork and then accept in the parent and read the child's message
and close the socket. this would be so much easier if you used subs for
the parent and the children and such. even better, learn to use event
loops which are the best way to handle socket i/o and such.
die "Unable to listen: $!\n";
while(my $conn = $listen->accept()) {
between the formatting and the lack of subs it is hard to tell if this
accept is happening in the (should be single) parent or in the child.
this shows the importance of clean coding.
warn "Got conn from ",$conn->peerhost,":",$conn->peerport,"\n";
my $line = $conn->read(1024);#do { local $/; <$conn>; };
if($line =~ /^(\d+):(\d+):.*/) {
print "Child with pid $1 from num $2 says $line\n";
}
else {
print "Invalid line : $line\n";
}
$conn->close();
}
exit(0);
}
elsif($pid == 0) {
my $sock = IO::Socket::INET->new(
PeerAddr => "127.0.0.1:8989",
Proto => 'tcp',
);
you could simplify that with just passing in the host::port arg. that
sub assumes that will be a tcp address so the key/value stuff isn't
needed. it is the most common use and so it has a simpler api.
thanx,
uri
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/