raflach has asked for the wisdom of the Perl Monks concerning the following question:

Is the following code legal/possible/acceptable?
Assume that all variables are properly inited etc.
if ( $child = fork ) { #Do Parent stuff here } else { while ( $child2 = fork ) { # fork 2nd child, wait for wait; # it to finish and re-fork } # Do second level child stuff here # Every time we finish, child # 1 starts us again exit; }

If that is legal, then assume that I open a set of paired filehandles using pipe ( PARENTREAD, PARENTWRITE ); from the IO::Handle module.
Can I write from the secondary child and read from the first parent? i.e.
if ( $child = fork ) { close PARENTWRITE; # Not needed in parent while ( ! $child2data ) { $child2data = <PARENTREAD>; } # Do Parent stuff here # after ensuring that child2 started } else { close PARENTREAD; # Not needed in child # Do some processing while ( $child2 = fork ) { # fork 2nd child, wait for wait; # it to finish and re-fork } # Do second level child init stuff here print PARENTWRITE 1; # Let parent know we started good # Do more second level child processing # Every time we finish, child # 1 starts us again exit; }

Replies are listed 'Best First'.
Re: mutiple forks
by Fastolfe (Vicar) on Sep 27, 2000 at 23:08 UTC
    I don't see why not, though you're doing your read in the <STYLE>, which reads by lines, so your print statement needs to be altered slightly:
    print PARENTWRITE "1\n"; # perhaps something useful like $pid?
    You may also get bitten by the fact that PARENTWRITE is buffered. Don't expect communication between your two processes to be instantaneous. Use select(PARENTWRITE); $|=1; select(STDOUT); or the IO::Handle equivalent to change this behavior.
    Note: Code samples are for conceptual use only and generally are not meant to be cut/pasted into a production application. Always 'use strict', have a thorough understanding of the code you use, and check the return values of functions and handle errors according to your needs. - Fastolfe