如何在 Perl 中使用 fork() ?
我的数组中有数百个文件名。我想为数组中的每 4 个文件创建一个子进程,并让该子进程对这 4 个文件中的每一个文件执行一些操作。 (因此,对于 100 个文件,我将创建 25 个进程。)
我在理解存在分叉时处理行的顺序时遇到了一些困难。我在想我可以做这样的事情,但我陷入了困境:
foreach $file (@files) {
if ($f++ % 4 == 0) {
my $pid = fork();
if ($pid) {
push(@childs, $pid);
}
elsif ($pid == 0) {
... do stuff to $file ...
}
}
我认为这是不对的,我希望有人能指出我正确的方向。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除了使用
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:使用 Parallel::ForkManager
请注意,这仍然会创建 100 个进程,它只是将其限制为25个并发。
如果您确实只需要 25 个进程,可以使用以下命令:
Use Parallel::ForkManager
Note that this still creates 100 processes, it simply limits it to 25 concurrent.
If you truly want only 25 processes, you can use the following:
我将分组到一个数组,并让孩子处理该组
i would group to an array, and let the child handle that group