我看到了来自APUE的代码片段
dup2(fd,0); dup2(fd,1); dup2(fd, 2); if (fd > 2) close(fd);
在我的理解中,它使得stdin、stdout和stderr都指向fd。它说lots程序包含这段代码,为什么?它的功能是什么?
发布于 2015-06-02 08:55:23
我将在这里添加注释和答案,因为即使它们是正确的,我仍然很难确切地理解何时以及为什么需要这个调用序列。
当进程将作为守护进程运行时,通常使用此函数调用序列。在这种情况下,守护进程不希望将标准I/O文件描述符附加到终端(或其他资源)。要“分离”这些描述符,可能会发生如下情况:
int fd;
fd = open("/dev/null",O_RDWR); // missing from APUE exercise 3.4 example
if (fd != -1)
{
dup2 (fd, 0); // stdin
dup2 (fd, 1); // stdout
dup2 (fd, 2); // stderr
if (fd > 2) close (fd);
} 这样做的目的是首先绑定/dev/null' to each of the standard I/O descriptors and closes the temporary descriptor used to open/dev/null` (只要由于某种原因,open没有使用通常用于标准I/O描述符的描述符)。
现在守护进程有了有效的stdin/stdout/stderr描述符,但它们并没有引用可能会干扰另一个进程的文件或设备。
https://stackoverflow.com/questions/16333980
复制相似问题