zokxter
zokxter

Reputation: 397

IPC communication between 2 processes with Perl

Let's say we have a 'Child' and 'Parent' process defined and subroutines

my $pid = fork;
die "fork failed: $!" unless defined($pid);

local $SIG{USR1} = sub {
kill KILL => $pid;
$SIG{USR1} = 'IGNORE';
kill USR1 => $$;
};

and we divide them, is it possible to do the following?

if($pid == 0){
    sub1();
#switch to Parent process to execute sub4()
    sub2();
#switch to Parent process to execute sub5()
    sub3();
}
else
{
    sub4();
#send message to child process so it executes sub2
    sub5();
#send message to child process so it executes sub3
}  

If yes, can you point how, or where can I look for the solution? Maybe a short example would suffice. :)

Thank you.

Upvotes: 1

Views: 1796

Answers (1)

Sobrique
Sobrique

Reputation: 53478

There is a whole page in the docs about inter process communication: perlipc

To answer your question - yes, there is a way to do what you want. The problem is, exactly what it is ... depends on your use case. I can't tell what you're trying to accomplish - what you you mean by 'switch to parent' for example?

But generally the simplest (in my opinion) is using pipes:

#!/usr/bin/env perl
use strict;
use warnings;
pipe ( my $reader, my $writer ); 
my $pid = fork(); #you should probably test for undef for fork failure. 
if ( $pid == 0 ) { 
    ## in child:
    close ( $writer );
    while ( my $line = <$reader> ) {
        print "Child got $line\n";
    }
}
else {
    ##in parent:
    close ( $reader );
    print {$writer} "Parent says hello!\n";
    sleep 5;
}

Note: you may want to check your fork return codes - 0 means we're in the child - a number means we're in the parent, and undef means the fork failed.

Also: Your pipe will buffer - this might trip you over in some cases. It'll run to the end just fine, but you may not get IO when you think you should.

You can open pipes the other way around - for child->parent comms. Be slightly cautious when you multi-fork though, because an active pipe is inherited by every child of the fork - but it's not a broadcast.

Upvotes: 2

Related Questions