首页 > 解决方案 > 获取标准输出 c 的文件描述符

问题描述

stdin、stdout、stderr 文件描述符默认为 0、1 和 2。但是,在我打开文件后fd = open(foo, 0),我发现fd现在是 1。1 用于新的文件描述符。现在标准输出文件描述符是什么?或者它已关闭,我需要重新打开它?如果是,如何?有没有办法保留 0、1、2 个文件描述符并从 3 中使用?

/* readslow from the book with my "improve": the unix programming environment */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define SIZE 512
int main (int argc, char *argv[])
{
    char buf[SIZE];
    int n, fd;
    int t = 10;

    if ((argc > 1) && (fd = open(argv[1], 0) == -1)) {error("can't open %s", argv[1]);}
    fprintf(stderr, "%d", fd);

    for (;;) {
        while ((n = read(fd, buf, sizeof buf)) > 0)
           write(1, buf, n);
        sleep(t);
    }
}

fprintf(stderr, "%d", fd)会给我1。

标签: cshell

解决方案


[撰写此答案时,问题中没有代码。open我已经接受了 OP 的说法,即由is返回的文件描述符1,由于放错了括号,结果证明这是不真实的。]

fd现在发现是 1。1 用于新的文件描述符。

发生这种情况的唯一方法是关闭 fd 1。

现在标准输出文件描述符是什么?

fileno(stdout)将为您fd提供与句柄相关联的信息。

有没有办法保留 0、1、2 个文件描述符并从 3 中使用?

如果不关闭 fd 0、1 和 2,它们将不会被重用。open使用编号最小的未使用文件描述符。

如果您想断开 fd 0、1 或 2,请不要关闭它们。这会导致各种问题。重新打开它们/dev/null

或者它已关闭,我需要重新打开它?如果是,如何?

您可以使用dup2使 fd 成为另一个 fd 的别名。


推荐阅读