将 `close` 替换为 `open` `/dev/null`?

Replacing `close` with `open` `/dev/null`?

我们有这样的 Perl 代码:

if (fork==0) {
  # in child process close STDOUT и STDERR, for the parent process didn't wait a response from the child and finished quickly
  close(STDOUT); 
  if (!defined fileno(CGI::Carp::SAVEERR)) {close(STDERR)} # TODO learn to close redirected STDERR
  else        { close(CGI::Carp::SAVEERR); } 

  # ...
}

我们遇到了 中描述的问题 - 为了解决它,建议我不要关闭 STDOUT,而是将其重新打开为“/dev/null”。

我是否应该将上面代码中对 close 的所有调用替换为 open /dev/null?或者只有 close(STDOUT)close(STDERR)?

这个替换会不会中断 "parent process didn't wait a response from the child and finished quickly"?

似乎有几件事需要弄清楚。

parent确实需要收获其child进程(waitwaitpidSIGCHLD ),如果这就是“等待 child 的响应”的意思。但是,如果 parent 先退出, child 是 init 的 re-parented,一切都很好。这不受 child 关闭(重新打开)其流的影响。

至于 "closing" 流,应该将它们重定向(重新打开)到 /dev/null。例如,请参阅问题中链接的 post 中的 Complete disassociation of child from parent in perlipc for how the streams are shut down for daemonization, and

最后,STDERR 似乎是 saved and redirected to a file in CGI::Carp。您现在是要关闭还是恢复它取决于 intent/design。如果 STDERR 要去的日志和流本身应该关闭你应该首先关闭日志,模块应该恢复什么 STDERR (请检查),然后将流重定向到 /dev/null.

总而言之,也许

my $pid = fork // die "Can't fork: $!";  #/

if ($pid == 0) 
{
    open STDOUT, '>', '/dev/null' or die "Can't write to /dev/null: $!";

    if (defined(fileno(CGI::Carp::SAVEERR)) 
    {
        close $fh_log_to_which_STDERR_was_redirected  or die $!;
        close CGI::Carp::SAVEERR                      or die $!;
    }    
    open STDERR, '>', '/dev/null' or die "Can't write to /dev/null: $!";
    ...
}

但请检查您的 CGI::Carp 处理方式,因为问题中没有相关信息。

未给出 fork 的上下文,但考虑 IPC::Run3 or IPC::Run 启动和管理流程。