gpt4 book ai didi

perl - 如何在 Perl 中使用 fork()?

转载 作者:行者123 更新时间:2023-12-04 02:40:27 30 4
gpt4 key购买 nike

我在一个数组中有数百个文件名。我想为数组中的每 4 个文件创建一个子进程,并让该子进程对这 4 个文件中的每一个执行一些操作。 (因此,对于 100 个文件,我将创建 25 个进程。)

我在理解 fork 时处理行的顺序时遇到了一些麻烦。我以为我可以做这样的事情,但我被卡住了:

foreach $file (@files) {
if ($f++ % 4 == 0) {
my $pid = fork();

if ($pid) {
push(@childs, $pid);
}
elsif ($pid == 0) {
... do stuff to $file ...
}
}

我不认为这是正确的,我希望有人能指出我正确的方向。谢谢。

最佳答案

除了您使用 fork 的麻烦之外,您似乎也无法对您的 @files 进行分区将数组分成四个文件的较小集合。也许是这样的:

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 - 如何在 Perl 中使用 fork()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8318414/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com