【发布时间】:2013-06-01 04:06:54
【问题描述】:
目前我正在尝试使用 perl 逐行读取文件并 fork 进程
基本上,我的 perl 脚本“test.pl”使用 exec 执行另一个脚本,它应该工作的方式是脚本“run.sh”应该为文件的每 5 行执行一次,使用文件行作为命令行参数exec 函数然后等待这 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
不幸的是,它没有按预期工作,它似乎读取随机行与顺序行相反我相信这是由于分叉过程,但我不确定如何解决它。
这个问题可能是相关的 Fork in Perl not working inside a while loop reading from file 但我还是很困惑。
test.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
test.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);
run.sh
sleep 5
echo "I was passed the following arg:"
echo $1
echo $2
【问题讨论】:
-
是否需要等待所有 5 个完成,或者一次最多有 5 个孩子跑步就足够了?
-
你得到什么输出,你期望什么输出?
-
您的代码甚至无法编译。
-
是的。需要删除严格和警告。
-
我为不工作的代码道歉,这是我从原始代码创建的一个坏例子。我只是希望你能看到我要归档的内容。
标签: linux perl bash while-loop line-by-line