我有一个哈希,当我尝试为每个哈希键创建一个子进程时,它的行为不符合我的预期.
请提出修改建议?
假设$pid从不小于0.
foreach $elem(keys %hash)
{
$pid = fork();
if ($pid)
{
push @pids, $pid;
print "in parent $$\n";
}
else
{
print "in child $$\n";
}
}
Run Code Online (Sandbox Code Playgroud)
执行子进程时,不要忘记退出,否则子进程也将执行fork,并且创建的进程总数将高于预期.
foreach $elem(keys %hash)
{
$pid = fork();
if ($pid)
{
push @pids, $pid;
print "in parent $$\n";
}
else
{
print "in child $$\n";
exit(0); #<--- add this or exec external program
}
}
Run Code Online (Sandbox Code Playgroud)