in reply to Using a stack with fork()

Why not just:
foreach my $host (@arrayofhosts) { defined (my $pid = fork) or die "Cannot fork: $!"; unless ($pid) { # go to town with $host exit 0; # very important!!! don't let it get past here } }

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: Re: Using a stack with fork()
by geektron (Curate) on Jan 06, 2001 at 07:14 UTC
    because that would fork-bomb a machine if the array is large.

    i did this in a previous script:

    my $fork_num = ( $#hostlist <= MAXFORK ? $#hostlist : MAXFORK ); for ( 0..$fork_num ) { ## ## create bi-directional socket for parent/child communication my $to_child = IO::Socket->new(); my $to_parent = IO::Socket->new(); socketpair($to_child, $to_parent, PF_UNIX, SOCK_STREAM, PF_UNSPEC) or die "Couldn't create socket pair: $!\n"; my $pid; if ( $pid = fork ) { ### parent process undef $to_parent; $to_child->autoflush; $children{$pid} = $to_child; sleep 1; next; } else { ### child process undef $to_child; undef %children; $to_parent->autoflush(1); local $SIG{PIPE} = sub { print " CAUGHT PIPE\n\n"; die "Signal caught in +Child $$: $!\n"; }; ## ## main processing occurs in the subroutine. &process_config_job($fork_num, $to_parent); } }

    the child processes have a sub getnexthost() which asks the parent for another hostname.

    the parent process has a subroutine to read the request for a new hostname then send it.

    i don't like the 'fork foreach' idiom. good way to crash a box.