in reply to Launching multiple processes

Quick solution using fork and exec.
my $program = '/bin/ls'; my $num_children = 5; $SIG{CHLD} = 'IGNORE'; for (1..$num_children) { defined ( my $pid = fork ) or die "Can not fork!"; if (!$pid) { # in child process exec $program; } }
Update: fixed the logical bug with fork, if fork returns pid of 0 (parent) the code would die too. undef and 0 both evaluates to false. Thanks to borisz to point out below. Zaxo is right too. ;-)

Replies are listed 'Best First'.
Re: Re: Launching multiple processes
by borisz (Canon) on Jan 06, 2004 at 23:16 UTC
    the fork line should be written as
    defined ( my $pid = fork ) or die "Can not fork!";
Re: Re: Launching multiple processes
by Zaxo (Archbishop) on Jan 07, 2004 at 00:01 UTC

    Another bug: You have the makings of a fine fork bomb. If I calculate right, you'll get 20 instances of /bin/ls from that. Call the child program with exec or else exit after system.

    Don't forget to zombie-proof it with wait or $SIG{CHLD), either.

    After Compline,
    Zaxo