bockman has asked for the wisdom of the Perl Monks concerning the following question:
#!/usr/bin/perl use strict; use warnings; use Socket; use constant LINE_LEN => 24; my $NUM_CHLDS = 5; # Five children my ($parent, $child) = (); my (@pids,$line) = (); my @chld_fh = (); my @par_fh = (); print "Forking..."; for(0 .. $NUM_CHLDS) { $pids[$_] = { child_fh => 0, parent_fh => 0, pid => 0 }; socketpair($pids[$_]->{child_fh},$pids[$_]->{parent_fh}, AF_UNIX,SOCK_STREAM,PF_UNSPEC) or die "socketpair at $_: $!\n"; unless(($pids[$_]->{pid} = fork())) { # Child die "cannot fork at $_: $!" unless defined $pids[$_]->{pid}; close $pids[$_]->{child_fh}; print "$$: Getting line\n"; sysread($pids[$_]->{parent_fh},$line,LINE_LEN); $line = "$$: " . reverse $line . int(rand(10)); print "$$: Sending line back\n"; syswrite($pids[$_]->{parent_fh},$line,LINE_LEN); close $child; syswrite($pids[$_]->{parent_fh},$line,LINE_LEN); close $child; exit; } print "1.."; } print "\n"; # Parent # chomp($line = <STDIN>); print "$$: Got string, writing\n"; for(0 .. $NUM_CHLDS) { close $pids[$_]->{parent_fh}; syswrite($pids[$_]->{child_fh},$line,LINE_LEN); } print "$$: Wrote, waiting\n"; sleep 1; # For fun for(0 .. $NUM_CHLDS) { sysread($pids[$_]->{child_fh},$line,LINE_LEN); print "Parent pid $$ just read: '$line'\n"; close $pids[$_]->{child_fh}; } wait;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Socketpair and a lot of children
by japhy (Canon) on Feb 25, 2006 at 03:53 UTC | |
by bockman (Sexton) on Feb 25, 2006 at 04:35 UTC | |
|
Re: Socketpair and a lot of children
by NetWallah (Canon) on Feb 25, 2006 at 07:07 UTC | |
|
Re: Socketpair and a lot of children
by ayrnieu (Beadle) on Feb 25, 2006 at 13:14 UTC |