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 Pe开发者_Go百科rl 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...
- system() works, but executes the commands consecutively (makes sense per documentation)
- exec() doesn’t work - it only executes the first method (makes sense per doc)
- I added a fork() to the child Perl script and then tried using system()
- this did not work either.
- backtick command ' documents says it works the same as system()...
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?
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
A very lightweight approach.
Windows:
foreach my $cmd (@cmds)
{
`start $cmd`;
}
Unix:
foreach my $cmd (@cmds)
{
`$cmd &`;
}
A module is overkill for this job. You want to fork
to create a new process and then exec
to run a command in the new process. To run five commands, you need something like:
for (my $i=0; $i<5; $i++) {
if (fork() == 0) {
exec($command[$i]); # Runs command and doesn't return
}
}
You need to fork in the parent, and then exec in the new process. It goes like this, assuming A is the original script, and B is the one you want to do 5 times:
A1
fork in A1 -> A1 A2
exec B in A2 -> A1 B2
fork in A1 -> A1 A3 B2
exec B in A3 -> A1 B3 B2
etc.
精彩评论