#!/usr/bin/perl =head1 NAME child_to_parent_ipc_demo - child process reports on it's status to the parent =head1 SYNOPSIS child_to_parent_ipc_demo =head1 DESCRIPTION A demonstration of a technique of spinning off a child process which can report on it's progress back to the parent process, while letting the parent go off and do some other things. =cut use warnings; use strict; # $|=1; our $VERSION = 0.01; use IO::Handle; # brings in autoflush and blocking # first set up a bi-directional pipe, # (will later close one direction) my ($reader, $writer); pipe $reader, $writer; $writer->autoflush(1); # still needed, even with modern perls $reader->blocking(0); # keeps reads from hanging my $pid; if ($pid = fork) { # this is parent code close $writer; print "Parent $$ is hearing from child $pid:\n"; while (1) { my $status = ''; $status = <$reader>; # magic "blocking(0)" keeps # this from blocking if ( defined( $status ) and ( $status =~ m{ ^ \d+ $ }xms ) ){ # recieved an update child process status chomp( $status ); print "\n$status% "; if ( $status >= 90 ) { close $reader; print "\n"; exit; } } else { # can continue doing stuff here while child is running print "."; sleep 1; } } } else { # this is child code die "cannot fork: $!" unless defined $pid; close $reader; # child code that takes awhile, but reports on it's status for my $i (1..10) { # the child takes a varying amount of time my $pause = int( rand(4) + .5 ); sleep $pause; my $status = $i * 10; print $writer "$status\n"; } close $writer; # i/o doesn't go through until closed, # *unless* autoflush is set to 1 exit; } __END__ =head1 SEE ALSO L The Perl Cookbook, 2nd ed. Chapter 16 (interprocess communication) Chapter 7 (non-blocking i/o) =head1 AUTHOR Joseph Brenner, Edoom@kzsu.stanford.eduE =head1 COPYRIGHT AND LICENSE Copyright (C) 2008 by Joseph Brenner This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.2 or, at your option, any later version of Perl 5 you may have available. =head1 BUGS None reported... yet. =cut