下面是解释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;
}
谢谢。这解释了它 – DesirePRG