目前,我正在尝试使用 perl 逐行读取文件并 fork 进程
基本上我的perl脚本“test.pl”使用exec执行另一个脚本它应该工作的方式是脚本“run.sh”应该使用文件行作为exec函数中的命令行参数为文件的每5行执行一次等待这 5 个过程完成并继续。
Line: 1 - run.sh executed
Line: 2 - run.sh executed
Line: 3 - run.sh executed
Line: 4 - run.sh executed
Line: 5 - run.sh executed - WAIT HERE for "run.sh" to complete then continue
Line: 6 - run.sh executed
Line: 7 - run.sh executed
Line: 8 - run.sh executed
Line: 9 - run.sh executed
Line: 10 - run.sh executed
不幸的是,它没有按预期工作,它似乎读取随机行与顺序行相反我相信这是由于分叉过程,但我不确定如何解决它。
这个问题可能与 Perl 中的 Fork not working inside a while loop reading from file有关,但我仍然很困惑。
测试.txt
5-6
7-1
5-9
1-22
8-55
9-6
3-5
7-1
5-9
1-22
8-55
9-6
3-5
测试.pl
$count = 0;
open (MYFILE, 'test.txt');
while (<MYFILE>) {
$data = $_;
$data =~ s/\R//g;
chomp();
my $pid = fork();
if ($pid == -1) {
die;
} elsif ($pid == 0) {
exec './run.sh', "-r $data" or die;
print $count;
}
if( ($count%5) == 0 ){
while (wait() != -1) {}
}
$count ++;
}
close (MYFILE);
运行.sh
sleep 5
echo "I was passed the following arg:"
echo $1
echo $2