下面是解释dup2 系统调用的代码段。我不明白的是,在复制了两个文件描述符之后,为什么我们需要关闭旧的文件描述符。由于“out”描述符现在已关闭,发送到 stdout_fileno 的消息如何也写入“out”。请注意,代码不是我写的。
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(){
int out;
out=open("out",O_WRONLY | O_TRUNC | O_CREAT,S_IRUSR|S_IRGRP | S_IWGRP | S_IWUSR);
dup2(out,STDOUT_FILENO);
close(out);
printf("now this should be written to a file called out \n");
return 0;
}
最佳答案
why do we need to close the old file descriptor
你真的不需要;这个例子主要说明你可以。然而,Unix 系统上的每个进程都有有限数量的文件描述符供其使用,当你有两个引用同一个文件时,其中一个是不必要的,所以你最好关闭它。
Since "out" descriptor is closed now, how does a message sent to stdout_fileno gets written to "out" as well.
因为在 dup2
之后,STDOUT_FILENO
也引用该文件,并且关闭 fd 不会关闭其克隆。
关于关闭文件描述符然后使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16795775/