当编写守护进程时,我希望关闭标准输入、标准输出和标准错误以实现“良好的守护进程行为”。但是我感到惊讶。后续打开文件需要与旧的标准输入、标准输出和标准错误具有相同的属性(因为它们的文件描述符被重新打开了?)
以下是warn.pl:
我原本期望没有警告,且$? == 0。这个问题是在我的代码中还是在perl中?这可能与此问题相似:如何重新初始化Perl的STDIN/STDOUT/STDERR?,但那里的解决方案是关闭STDIN、STDOUT和STDERR,就像我所做的一样。
以下是warn.pl:
use warnings;
my $nrWarnings = 0;
$SIG{__WARN__} = sub {
no warnings;
$nrWarnings++;
open my $log, '>>', '/tmp/log.txt'
or die;
printf $log "%d: %s", $nrWarnings, @_;
close $log;
};
close STDOUT;
close STDERR;
close STDIN;
open my $o, '>', '/tmp/foobar.txt'
or die;
open my $i, '<', '/etc/passwd'
or die;
open my $i2, '<', '/etc/passwd'
or die;
open my $i3, '<', '/etc/passwd'
or die;
exit $nrWarnings;
现在我来运行它:
> rm -f /tmp/log.txt ; perl warn.pl; echo $? ; cat /tmp/log.txt
3
1: Filehandle STDIN reopened as $o only for output at warn.pl line 20.
2: Filehandle STDOUT reopened as $i only for input at warn.pl line 22.
3: Filehandle STDERR reopened as $i2 only for input at warn.pl line 24.
我原本期望没有警告,且$? == 0。这个问题是在我的代码中还是在perl中?这可能与此问题相似:如何重新初始化Perl的STDIN/STDOUT/STDERR?,但那里的解决方案是关闭STDIN、STDOUT和STDERR,就像我所做的一样。