File: multichild.pl

package info (click to toggle)
libproc-fork-perl 0.807-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 136 kB
  • sloc: perl: 165; makefile: 2
file content (36 lines) | stat: -rw-r--r-- 789 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use strict;
use Proc::Fork;
use IO::Pipe;

my $num_children = 5;    # How many children we'll create
my @children;            # Store connections to them
$SIG{CHLD} = 'IGNORE';   # Don't worry about reaping zombies

# Spawn off some children
for my $num ( 1 .. $num_children ) {
	# Create a pipe for parent-child communication
	my $pipe = IO::Pipe->new;

	# Child simply echoes data it receives, until EOF
	run_fork { child {
		$pipe->reader;
		my $data;
		while ( $data = <$pipe> ) {
			chomp $data;
			print STDERR "child $num: [$data]\n";
		}
		exit;
	} };

	# Parent here
	$pipe->writer;
	push @children, $pipe;
}

# Send some data to the kids
for ( 1 .. 20 ) {
	# pick a child at random
	my $num = int rand $num_children;
	my $child = $children[$num];
	print $child "Hey there.\n";
}