pipes from forked processes

C

Corey_G

I have some code that forks processes which then go off and do some
work. I am trying to make it so child processes can communicate back
to the parent that spawned them. From what I have read, it looks like
I want to use Pipes.

I also want to make sure this is portable to Windows. In the perlfork
documentation, it states: "The open(FOO, "|-") and open(BAR, "-|")
constructs are not yet implemented. This limitation can be easily
worked around in new code by creating a pipe explicitly." which then
goes on to give some sample code that doesn't work.. great.

So I am now looking at using either IO::pipe or POE:pipe to do this
for me. Documentation for both is pretty sparse and the samples
aren't enough to get me going.

Does anyone have a sample piece of code using either of these modules
along with forking?

-Corey Goldberg
 
R

Rocco Caputo

So I am now looking at using either IO::pipe or POE:pipe to do this
for me. Documentation for both is pretty sparse and the samples
aren't enough to get me going.

If you're using POE, you may want to look at POE::Wheel::Run. Also
IPC::Run if you're not. Both modules implement the pipe/fork/exec
pattern, although the POE one does for spawning processes from within
that framework.
 
C

Corey_G

I finally figured out what I am doing thanks to this post from Bob
Showalter.

http://groups.google.com/groups?hl=...499D41199D200A0C9B15BC001D7EE62@FRISTX&rnum=2

he does this and it works great:


#!/usr/bin/perl

use strict;
$| = 1;
my $nc = 3; # number of children to create
pipe READER, WRITER; # pipe for communication

for my $c (1 .. $nc) {
# create a child process
defined(my $pid = fork) or die "Couldn't fork: $!";
next if $pid; # parent loops to create next child

# child does it's thing and writes back to parent through pipe
close READER;
select WRITER;
$| = 1;
print "Hello, I am child $c, and my PID is $$\n";
sleep rand(5) + 1;
print "Goodbye from child $c\n";
exit; # child exits (IMPORTANT!)
}

# parent reads from children
# pipe will close when last child exits
close WRITER;
while(<READER>) {
print $_;
}

1 while wait() > 0; # reap all exit statuses



Sample output:

$ perl myscript.pl
Hello, I am child 1, and my PID is 16774
Hello, I am child 2, and my PID is 16775
Hello, I am child 3, and my PID is 16776
Goodbye from child 2
Goodbye from child 1
Goodbye from child 3
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top