windows - "system"的 Perl Windows 替代品(打开多个进程)

标签 windows perl multiprocessing system

长话短说,我正在尝试在 Windows 中运行 Linux Perl 脚本(只需少量修改)。

在 Unix 上它工作得很好,但在 Windows 上我得出的结论是调用系统的工作方式与在 Unix 上不同,因此它不会创建多个进程。

下面是代码:

use strict;
use warnings;
open (FIN, 'words.txt'); while (<FIN>) {
   chomp;
   my $line = $_;
   system( "perl script.pl $line &" );
   
}
close (FIN);

所以基本上,我在“words.txt”中有5个不同的单词,我希望在调用 script.pl 时逐一使用每个单词,这意味着:

word1 script.pl
word2 script.pl
word3 script.pl
etc

到目前为止,它仅打开words.txt 中的第一个单词,并且仅循环使用该单词。正如我所说,在 Unix 上它工作得很好,但在 Windows 上却不行。

我尝试使用“start”system(“start perl script.pl $line &”);并且它有效......除了它打开5个额外的CMD来完成工作。我希望它在同一个窗口上完成工作。

如果有人知道这如何在窗口上工作,我将非常感激。

谢谢!

最佳答案

根据perlport :

system

(Win32) [...] system(1, @args) spawns an external process and immediately returns its process designator, without waiting for it to terminate. Return value may be used subsequently in wait or waitpid. Failure to spawn() a subprocess is indicated by setting $? to 255 << 8. $? is set in a way compatible with Unix (i.e. the exit status of the subprocess is obtained by $? >> 8, as described in the documentation).

我尝试过这个:

use strict;
use warnings;
use feature qw(say);
say "Starting..";
my @pids;
for my $word (qw(word1 word2 word3 word3 word5)) {
    my $pid = system(1, "perl script.pl $word" );
    if ($? == -1) {
        say "failed to execute: $!";
    }
    push @pids, $pid; 
}

#wait for all children to finish
for my $pid (@pids) {
    say "Waiting for child $pid ..";
    my $ret = waitpid $pid, 0;
    if ($ret == -1) {
        say " No such child $pid";
    }
    if ($? & 127) {
        printf " child $pid died with signal %d\n", $? & 127;
    }
    else {
        printf " child $pid exited with value %d\n", $? >> 8;
    }
}
say "Done.";

使用以下子脚本script.pl:

use strict;
use warnings;
use feature qw(say);
say "Starting: $$";
sleep 2+int(rand 5);
say "Done: $$";
sleep 1;
exit int(rand 10);

我得到以下输出:

Starting..
Waiting for child 7480 ..
Starting: 9720
Starting: 10720
Starting: 9272
Starting: 13608
Starting: 13024
Done: 13608
Done: 10720
Done: 9272
Done: 9720
Done: 13024
 child 7480 exited with value 9
Waiting for child 13344 ..
 child 13344 exited with value 5
Waiting for child 17396 ..
 child 17396 exited with value 3
Waiting for child 17036 ..
 child 17036 exited with value 6
Waiting for child 17532 ..
 child 17532 exited with value 8
Done.

看起来工作正常..

关于windows - "system"的 Perl Windows 替代品(打开多个进程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69682218/

相关文章:

windows - 从 DMZ 连接到 Active Directory 的最安全方法是什么?

Perl XML::Twig 问题请

Python多进程运行多次

python - 如何从python进程池中获取进程

c++ - 从 C++ 类制作 Visual C++ DLL

java - 如何检查批处理文件是否正在 Windows 上运行?

node.js - 安装 gulp 到 windows 10

perl - 仅选择第一个元素 - 条件使用 XML::Twig

perl - 在 @INC 中找不到 LWP/Simple.pm

python - 使用多处理池时的 Pycharm 调试器