如何重新初始化 Perl 的 STDIN/STDOUT/STDERR? [英] How can I reinitialize Perl's STDIN/STDOUT/STDERR?
问题描述
我有一个 Perl 脚本,它可以对自身进行分叉和守护进程.它由 cron 运行,所以为了不留下僵尸,我关闭了 STDIN、STDOUT 和 STDERR:
I have a Perl script which forks and daemonizes itself. It's run by cron, so in order to not leave a zombie around, I shut down STDIN,STDOUT, and STDERR:
open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
if (!fork()) {
do_some_fork_stuff();
}
我的问题是:我想在此之后至少恢复 STDOUT(恢复其他 2 个会很好).但是我需要使用什么魔法符号来重新打开 STDOUT 就像以前的 STDOUT 一样?
The question I have is: I'd like to restore at least STDOUT after this point (it would be nice to restore the other 2). But what magic symbols do I need to use to re-open STDOUT as what STDOUT used to be?
我知道如果我从 tty 运行,我可以使用/dev/tty"(但我从 cron 运行并且依赖于其他地方的 stdout).我还阅读了一些技巧,您可以通过 open SAVEOUT,">&STDOUT"
将 STDOUT 放在一边,但只是制作此副本的行为并不能解决留下僵尸的原始问题.
I know that I could use "/dev/tty" if I was running from a tty (but I'm running from cron and depending on stdout elsewhere). I've also read tricks where you can put STDOUT aside with open SAVEOUT,">&STDOUT"
, but just the act of making this copy doesn't solve the original problem of leaving a zombie around.
我想看看是否有一些魔法,比如 open STDOUT,"|-"
(我知道不是这样)以它应该打开的方式打开 STDOUT.p>
I'm looking to see if there's some magic like open STDOUT,"|-"
(which I know isn't it) to open STDOUT the way it's supposed to be opened.
推荐答案
如果它仍然有用,我会想到两件事:
If it's still useful, two things come to mind:
您可以仅在子进程中关闭 STDOUT/STDERR/STDIN(即 if (!fork()).这将允许父进程仍然使用它们,因为它们仍然在那里打开.
You can close STDOUT/STDERR/STDIN in just the child process (i.e. if (!fork()). This will allow the parent to still use them, because they'll still be open there.
我认为您可以使用更简单的 close(STDOUT) 而不是将其打开到/dev/null.
I think you can use the simpler close(STDOUT) instead of opening it to /dev/null.
例如:
if (!fork()) {
close(STDIN) or die "Can't close STDIN: $!
";
close(STDOUT) or die "Can't close STDOUT: $!
";
close(STDERR) or die "Can't close STDERR: $!
";
do_some_fork_stuff();
}
这篇关于如何重新初始化 Perl 的 STDIN/STDOUT/STDERR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!