How can I execute an external Windows command and instantly return in Perl?

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 &`;
}

Tags:

Windows

Perl