关闭文件描述符然后使用它

标签 c unix posix file-descriptor dup2

下面是解释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/

相关文章:

c - 遍历 const 矩阵和 vector

linux - 在 Linux 上连接和使用多个蓝牙加密狗?

ios - 获取 WKWebView 的当前内存使用情况?

c - c中的递归函数中的内存泄漏

c - (void) 与寄存器值的不明确使用

linux - 如何使用 Bash 更改类型为 "find"的文件的扩展名?

php - PHP中的进程间通信

c - posix在线程中创建共享内存

shell - `for NAME do ...` 中的 NAME 后是否禁止使用分号?

c - C 中的不可整子集 Hackerrank 解决方案