无法运行 Fork,分叉了不需要的进程数
我在 Perl 中使用 Fork 时遇到问题。我想从一个脚本一次性执行 10 个分叉进程,所有 10 个子(分叉)进程都会执行相同的操作(将文件从一个位置复制到另一个位置)。
当我执行这段代码时,我的操作系统挂起,当我实际检查时,有很多进程同时被分叉。
这是我的代码:
while ($callCount <= $totalCalls) {
for (1..$TotalProcessToFork) {
print "Call -> $callCount";
if($pid = fork) {
#in Parent Process
print " :: PID -> $pid\n";
push(@list_of_pid, $pid);
} else {
#in Child Process
`touch $callCount`;
}
$callCount++;
}
}
现在,当我执行此代码时,大约有 1000 个子进程被执行。
谁能告诉我我在这里做错了什么。
I am having an issue with Fork in Perl. I want to execute 10 Fork Processes at a go from one single script all 10 Child (Forked) processes will do the same thing (Copy files from one place to another).
When I execute this code, my OS Hangs and when I actually check there are hell lot of processes which are forked at a time.
Here is my Code:
while ($callCount <= $totalCalls) {
for (1..$TotalProcessToFork) {
print "Call -> $callCount";
if($pid = fork) {
#in Parent Process
print " :: PID -> $pid\n";
push(@list_of_pid, $pid);
} else {
#in Child Process
`touch $callCount`;
}
$callCount++;
}
}
Now when I execute this code, there are around 1000 child processed which are executed.
Can any one tell me what wrong I am doing here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
孩子们也用叉子。您需要在子案例中以一种或另一种方式退出循环。常见的模式是 fork 和 exec,或者您可以只说
last
。The children fork, too. You need to exit the loop one way or another in the child case. A common pattern is to fork and exec, or you could just say
last
.发生这种情况是因为当您分叉一个进程时,它会创建两个进程。我们称它们为
a1
和a2
。现在a1
是父级,a2
是子级,因此当执行a2
时,它会创建b1
和 <代码>b2。当这些都被执行时,它们还会递归地创建新的进程。This happens because when you fork a process, it creates two processes. Lets call them
a1
anda2
. Nowa1
is the parent anda2
is the child, so whena2
is executed, it createsb1
andb2
. When these all are executed, they also create new processes recursively.您可能需要查看
Parallel::ForkManager
,这可能会让您的生活更轻松。另外,不要使用外部 Linux
touch
命令;最好使用File::Touch
。You may want to take a look at
Parallel::ForkManager
, which will probably make your life easier.Also, don't use external Linux
touch
command; it's better to useFile::Touch
.独立于 Perl:了解 fork 是如何工作的!
在循环中,被分叉的第一个进程继续执行循环`` $TotalProcessToFork -1
次,由原始父进程分叉的第二个进程将执行循环
$TotalProcessToFork -2`次,所以on...此外第一个子进程分叉的第一个子进程也会执行循环
$TotalProcessToFork -3
次。也许试试这个代码:
当我运行它时,我得到了这个输出:
Independent of Perl: Learn how fork works!
In your loop the first process being forked continues to execute the loop `` $TotalProcessToFork -1
times, the second process being forked by the original parent will execute the loop
$TotalProcessToFork -2` times, and so on...In addition the first child forked by the first child will also execute the loop
$TotalProcessToFork -3
times.Maybe try this code:
When I ran it, I got this output: