長話短說,我正在嘗試在 Windows 中運行一個 linux perl 腳本(幾乎沒有修改)。
在 Unix 上它作業得很好,但在 Windows 上我得出的結論是,呼叫 system 與在 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 上則不行。
我嘗試使用“啟動”系統(“啟動 perl script.pl $line &”);它可以作業……除了它打開 5 個額外的 CMD 來完成這項作業。我希望它在同一個視窗上完成作業。
如果有人知道這如何在視窗上作業,我將非常感激。
謝謝!
uj5u.com熱心網友回復:
根據perlport:
系統
(Win32) [...]
system(1, @args)生成一個外部行程并立即回傳其行程指示符,而無需等待它終止。回傳值可隨后在wait或 中使用waitpid。spawn()子行程失敗通過設定$?為 255 << 8 來指示。以$?與 Unix 兼容的方式設定(即子行程的退出狀態由 獲得$? >> 8,如檔案中所述)。
我試過這個:
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.
似乎作業正常..
uj5u.com熱心網友回復:
Win32::Process與system在 Windows 上相比,您可以使用來更好地控制創建新行程。特別是,以下不會像 usingsystem("start ...")那樣為每個行程創建一個新的控制臺:
#!/usr/bin/env perl
use warnings;
use strict;
use feature qw/say/;
# Older versions don't work with an undef appname argument.
# Use the full path to perl.exe on them if you can't upgrade
use Win32::Process 0.17;
my @lines = qw/foo bar baz quux/; # For example instead of using a file
my @procs;
for my $line (@lines) {
my $proc;
if (!Win32::Process::Create($proc, undef, "perl script.pl $line", 1,
NORMAL_PRIORITY_CLASS, ".")) {
$_->Kill(1) for @procs;
die "Unable to create process: $!\n";
}
push @procs, $proc;
}
$_->Wait(INFINITE) for @procs;
# Or
# use Win32::IPC qw/wait_all/;
# wait_all(@procs);
作為另一種方式做到這一點,該start命令需要一個/b選擇不打開一個新的命令提示符。
system("start /b perl script.pl $line");
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/335567.html
上一篇:在具有兩個以上處理器組的雙套接字系統上通過ctypes在Python中使用GetLogicalProcessorInformationEx()
