如何在Perl中使用fork()? [英] How to use fork() in Perl?
问题描述
我在数组中有数百个文件名.我想为数组中的每个4个文件创建一个子进程,并让该子进程对这4个文件中的每个文件进行处理. (因此,使用100个文件,我将创建25个进程.)
I have hundreds of file names in an array. I want to create a child process for every 4 files in the array, and have that child do some stuff to each of those 4 files. (So with 100 files, I'll create 25 processes.)
我很难理解有叉子时处理行的顺序.我以为我可以做这样的事情,但是我被卡住了:
I'm having some trouble understanding the order in which lines are processed when there's a fork. I was thinking I could do something like this, but I'm getting stuck:
foreach $file (@files) {
if ($f++ % 4 == 0) {
my $pid = fork();
if ($pid) {
push(@childs, $pid);
}
elsif ($pid == 0) {
... do stuff to $file ...
}
}
我认为这是不对的,我希望有人能指出我正确的方向.谢谢.
I don't think this is right, and I'm hoping someone can point me in the right direction. Thanks.
推荐答案
除了使用fork
的麻烦外,您似乎还无法将@files
数组划分为四个较小的文件集.也许是这样的:
In addition to your trouble using fork
, you also seem to have trouble partitioning your @files
array into smaller sets of four files. Maybe something like this:
for (my $i = 0; $i < @files; $i += 4) {
# take a slice of 4 elements from @files
my @files4 = @files[$i .. $i + 3];
# do something with them in a child process
if (fork() == 0) {
... do something with @files4 ...
exit; # <--- this is very important
}
}
# wait for the child processes to finish
wait for 0 .. @files/4;
这篇关于如何在Perl中使用fork()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!