tags:

views:

61

answers:

1

Can anyone explain how I can successfully get my processes communicating? I find the perldoc on IPC confusing.

What I have so far is:

$| = 1;
$SIG{CHLD} = {wait};
my $parentPid = $$;

if ($pid = fork();) ) {
    if ($pid == 0) {
       pipe($parentPid, $$);
       open PARENT, "<$parentPid";
       while (<PARENT>) {
           print $_;
       }
       close PARENT;
       exit();
    } else {

       pipe($parentPid, $pid);
       open CHILD, ">$pid";
          or error("\nError opening: childPid\nRef: $!\n");
       open (FH, "<list")
          or error("\nError opening: list\nRef: $!\n");

       while(<FH>) {
          print CHILD, $_;
       }

       close FH
          or error("\nError closing: list\nRef: $!\n");
       close CHILD
          or error("\nError closing: childPid\nRef: $!\n);
    } else {
    error("\nError forking\nRef: $!\n");
}
  • First: What does perldoc pipe mean by READHANDLE, WRITEHANDLE?

  • Second: Can I implement a solution without relying on CPAN or other modules?

alt text

+3  A: 

Here is a simplified example based on code found in perldoc perlipc:

#!/usr/bin/perl

use strict; use warnings;

$SIG{CHLD} = sub { wait };

pipe my $reader, my $writer;

my $pid = fork;
defined $pid or die "fork failed: $!";

if ( $pid ) { # parent
    close $reader;
    for my $n ( 1 .. 5 ) {
        select $writer;
        $| = 1;
        print $writer "Message $n\n"
            or die "Failed to pass message to child: $!";
        sleep 1;
    }
    close $writer;
    exit;
}
else { # child
    close $writer;
    while ( my $msg = <$reader> ) {
        print "Child received: $msg";
        last if rand > 0.5; # to check error handling in parent
    }
    close $reader;
    exit;
}
Sinan Ünür
THANK YOU!!! That is a really simple an easy to follow solution. Just one more question, how does "select $writer" know to write to the parent process?
Shiftbit
The `pipe` call connected `$reader` to `$writer`. Following `fork`, both filehandles are duplicated. `select $writer` is there so that the subsequent `$| = 1` operates on the correct filehandle (rather than whatever `STDOUT` is connected to).
Sinan Ünür
that makes sense. I came across an image, while researching a solution, that described what you were talking about, but there was no code to reference against. Great answer!
Shiftbit
My original answer confused the parent and the child processes. It's getting late here.
Sinan Ünür