I've tried using system() with fork(), tried exec(), and am still not getting what I need.
I want to write a Perl script which executes, let's say, a different Perl script five times in a row (sending it different parameter values), but I have it run concurrently. I realize I could turn my script into a .pm file and reference it, but I'd prefer to keep the child script independent of the parent...
Isn't there a simple way in Perl (I'm using Windows XP) to execute a process, and not care about the return values or anything and just continue on into the next line of the parent script?
qx or backticks - running external command and capturing the output People knowing shell are familiar with the back-ticks `` that allow us to execute external commands and capture their output. In Perl you can use the back-ticks or the qx operator that does exactly the same, just makes the code more readable.
Perl’s system() function executes a system shell command. Here the parent process forks a child process, and then waits for the child process to terminate. The command will either succeed or fail returning a value for each situation. The value 0 is returned if the command succeeds and the value 1 is returned if the command fails.
People knowing shell are familiar with the back-ticks `` that allow us to execute external commands and capture their output. In Perl you can use the back-ticks or the qx operator that does exactly the same, just makes the code more readable.
Points to Keep in Mind While Using Perl System Command. The return value of this function is the exit status of the program. The latter is returned by the wait function. In order to get the actual exit value divide the present value by the number 256.
You can do it like this (fork in the parent, exec in the child):
for my $cmd qw(command1 command2 command3) {
exec $cmd unless fork
}
The way that exec $cmd unless fork
works is that fork
will return a true value in the parent (the process id) and will return a false value in the child, thus exec $cmd
only gets run if fork
returns false (aka, in the child).
Or if you want to keep tabs on the process as it runs concurrently:
my @procs;
for my $cmd qw(cmd1 cmd2 cmd3) {
open my $handle, '-|', $cmd or die $!;
push @procs, $handle;
}
Then you can read from an element of @procs
if you need to.
Or take a look at one of the many CPAN modules, like Forks::Super
that handle the details of fork management.
On Windows, you can give the super-secret 1
flag to the system, IIRC.
system 1, @cmd;
A Google search for this question on PerlMonks gives: Start an MS window in the background from a Perl script
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With