I composed this ditty to demonstrate how to let one child process collect data from many client processes forked from the same parent. This was motivated by suaveant's question about speedy local IPC at Fastest way to talk to a perl daemon.
This demo program shows how the file descriptor for the write end of a pipe is duplicated on fork, allowing many processes to share it.
The select... while kill $ppid, 0; line in the client code is there just to keep the kids idle until the parent has departed. That is to avoid waiting or ignoring SIGCHLD. A persistent parent server would need to clean up after the kids.
#!/usr/bin/perl use warnings; use strict; my ( $ppid, $in, $out) = $$; pipe ( $in, $out) or die $!; # "Daemon" { local *STDIN = $in; local $| = 1; my $child; defined( $child = fork) or die $!; last if $child; close $out or die $!; print while <STDIN>; exit 0; } # Spawn some client processess { local *STDOUT = $out; local $| = 1; for my $kid (1..50) { my $child; defined( $child = fork) or die $!; next if $child; close $in; select( undef, undef, undef, .001) while kill $ppid, 0; select( undef, undef, undef, rand(1000)/1000), print 'Child ', $kid, ' pid=', $$, ' message=', 0 | rand 10000, $/ for 1..20; exit 0; } }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Many-to-One pipe
by RMGir (Prior) on Aug 07, 2002 at 12:14 UTC | |
by particle (Vicar) on Aug 07, 2002 at 12:50 UTC | |
Re: Many-to-One pipe
by cmv (Chaplain) on Sep 12, 2014 at 15:17 UTC |