Hi. I want to use socketpair() to talk from the parent to a lot of children. But I can't get it to work correctly. The error is: 'Can't use string ("0") as a symbol ref while "strict refs" in use.' How am I doing that? What did I do incorrectly? Also, is there a better way to talk to a bunch of children (and vice versa)? Here is my code:
#!/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;

In reply to Socketpair and a lot of children by bockman

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.