Last time, I linked to some example code that forks a bunch of processes and communicates with them via pipes. This is the main feature of the code I’m interested in, but the explanation is the article is kinda sparse so you can consider this to be supplemental.
As usual, the perl doco is pretty good for covering this stuff.
Creating a child process (a kid) involves two pipes, one for the parent to send data to the kid, and one for the kid to send data back to the parent.
One probably obvious thing to note, you can’t directly send a reference down a pipe, (well, not in any reasonable way and that’s a feature, not a bug), so you’ll be interested in serialisation modules. I’ve mentioned them in passing before and I generally use JSON::XS these days.
Another hopefully obvious thing is if the writer is buffered and the reader is waiting for something specific, there will probably be some deadlock in your future. Remember to unbuffer the writer.
I made a couple more J – comments inline:
sub create_kid { my $to_kid = IO::Pipe->new; my $from_kid = IO::Pipe->new; # J - Fork returns undef for failure, 0 for the child, and the # J - child PID for the parent # J - Handle fork error defined (my $kid = fork) or return; # if can't fork, try to make do unless ($kid) { # I'm the kid # J - The kid reads from $to_kid and writes to $from_kid $to_kid->reader; $from_kid->writer; # J - unbuffer writing to the pipes. Otherwise may deadlock $from_kid->autoflush(1); # J - Reset all of the signal handling $SIG{$_} = 'DEFAULT' for grep !/^--/, keys %SIG; # very important! do_kid($to_kid, $from_kid); exit 0; # should not be reached } # J - parent here... # J - The parent reads from $from_kid and writes to $to_kid $from_kid->reader; $to_kid->writer; # J - unbuffer writing to the pipes. Otherwise may deadlock $to_kid->autoflush(1); $kids{$kid} = [$to_kid, $from_kid]; $kid; }
Leave a Reply