以 ptunnel 方式关闭 stdin stdout 和 stderr

标签 c stdout stdin file-descriptor

我对 ptunnel 关闭 stdin、stdout 和 stderr 的方式很感兴趣:

if (daemonize)
{
    ...
    freopen("/dev/null", "r", stdin);
    freopen("/dev/null", "w", stdout);
    freopen("/dev/null", "w", stderr);
}

这是关闭它们的好方法吗?我很困惑,因为 freopen 将打开一个文件描述符,在这种情况下它不会关闭。

最佳答案

没有。这并不完全安全。

它假设 freopen() 重用相同的文件描述符,但不能保证。因此,如果 freopen() 使用不同的文件描述符,例如,对于 1 以外的 stdout,那么您随后的 write() 使用该文件描述符将无法按预期工作。因为 POSIX 读/写函数使用 *_FILENO 定义为:

/* Standard file descriptors.  */
#define STDIN_FILENO    0       /* Standard input.  */
#define STDOUT_FILENO   1       /* Standard output.  */
#define STDERR_FILENO   2       /* Standard error output.  */

针对相应的 IO 操作。

相反你可以这样做:

#include<unistd.h>

  fd = open("/dev/null",O_RDWR);
  dup2(fd,0);
  dup2(fd,1);
  dup2(fd,2); 

实现相同。明显的缺点是 open()dup2() 是 POSIX 函数,不是 C 标准的一部分。

但只要 freopen() 分别重用文件描述符 0、1 和 2,或者您不对可能不正确的文件描述符执行任何 IO,您就是安全的。

关于以 ptunnel 方式关闭 stdin stdout 和 stderr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16627543/

相关文章:

c - 从线程返回单个整数值

c - 在c中的伪随机数生成器中使用srand的时间函数

grep - 从标准输入读取 grep 表达式

c - float * 和 int * 的不同 printf 行为?

更改控制台窗口的窗口过程

c - 当给定无效路径时,freopen()创建一个文件

python - 捕获标准输出时 python2 和 python3 之间的 StringIO 可移植性

unicode - python 3.0,如何使print()输出unicode?

linux - stdin被占用时如何提示输入?

java - 将所有标准输入读入 Java 字节数组