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

i have written this program and would like to adapt it so that it would accept 1 to 3 commands and not just 3. and execute the commands if anyone could help it would be most appreciated.
#!/usr/local/bin/perl -w pipe PIPEIN1,PIPEOUT1;#pipe1 pipe PIPEIN2,PIPEOUT2;#pipe2 $command1=<STDIN>; # read command 1 from user chomp($command1); # remove new line character $command2=<STDIN>; # read command 2 from user chomp($command2); # remove new line character $command3=<STDIN>; # read command 3 from user chomp($command3); # remove new line character if (fork ==0)#child 1 { close PIPEIN1; # close pipe in 1 close PIPEIN2; # close pipe in 2 close PIPEOUT2; # close pipe out 2 close STDOUT; # close standard out open STDOUT, ">&PIPEOUT1"; #open standard out and pipe1 exec $command1; } if (fork==0)#child 2 { close PIPEIN2; #close pipe in 2 close PIPEOUT1; # close pipe out 1 close STDIN; # close standard in open STDIN, "<&PIPEIN1";# open standard in and pipe1 close STDOUT; # close standard out open STDOUT, ">&PIPEOUT2";# open standard out and pipe 2 exec $command2; } if (fork==0)#child 3 { close PIPEIN1; # close pipe in 1 close PIPEOUT1; # close pipe out 1 close PIPEOUT2; # close pipe out 2 close STDIN; # close standard in open STDIN, "<&PIPEIN2"; # open standard in and pipe in 2 exec $command3; } close PIPEIN1; # close pipe in 1 close PIPEOUT1; # close pipe out 1 close PIPEIN2; # close pipe in 2 close PIPEOUT2; # close pipe out 2 wait; # wait for child 1 to terminate wait; # wait for child 2 to terminate wait; # wait for child 3 to terminate

Edit - Masem added code tags
Edit - ar0n More descriptive title

Replies are listed 'Best First'.
(Knob)Re: Forking Multiple Children
by knobunc (Pilgrim) on Jun 19, 2001 at 16:36 UTC

    You appear to be passing the commands in to the standard input of the program. If there isn't a good reason for that then you can pass them on the command line:

    my ($command1, $command2, $command3) = @ARGV; $command2 = 'default' unless defined $command2; $command3 = 'hoo hah' unless defined $command3; # OR my $command1 = shift or die; # Ideally call a subroutine to print usag +e and die my $command2 = shift || 'default'; my $command3 = shift || 'hoo hah';

    If you have to read from STDIN then you can check to see if it still has stuff available using the eof function:

    my $command1 = <STDIN>; chomp($command1); my ($command2, $command3) = ('default', 'hoo hah'); unless (eof(STDIN)) { $command2 = <STDIN>; chomp $command2; unless (eof(STDIN)) { $command3 = <STDIN>; chomp $command3; } }

    -ben