【问题标题】:How to restore standard output's file descriptor?如何恢复标准输出的文件描述符?
【发布时间】:2012-02-09 10:46:43
【问题描述】:

我需要帮助来理解文件描述符

这是我的代码:

int main()
{
    char ch;
    close(1);
    //now opening a file so that it gets the lowest possible fd i.e. 1
    int fd=open("txt",O_RDWR);
    //check..
    printf("first printtf is executed\n");
    scanf("%c",&ch);
    printf("ur value is %c\n",ch);

    printf("second printf is executed\n");
    return 0;
}

在上述程序中,我尝试将printf 的输出重定向到txt 文件而不是标准输出,即终端。 但是如何恢复标准输出文件描述符,以便printf 在第二种情况下再次正常工作,即第二个printtf 应该只向终端输出..

【问题讨论】:

    标签: c linux printf system-calls file-descriptor


    【解决方案1】:

    最简单的方法是在关闭输出描述符之前复制它。你一定要看dup。

    【讨论】:

      【解决方案2】:

      在你关闭它之前,我想你想要 dup() 它。 当您需要它时,您可以 dup() dup。

      dup 将始终使用最低的描述符

      int out = dup(1);
      close(1);
      int fd = open();
      ...
      close(fd);
      dup(out);
      close(out);
      

      警告:这是来自记忆,未经测试;-)

      【讨论】:

      • 当 dup()-ing 它“返回”时,您必须使用 dup2 复制文件描述符在之前打开和关闭的 '1'。
      • 如果你关闭 fd 不会 dup 仍然这样做吗? (没有方便检查 dup2 的手册页)
      • 嗯,对,也许 dup() 会将其复制为 1...我认为它需要尝试!
      • 是的,先生,我刚刚尝试过,是的,dup 也在做这项工作,只要我关闭了最不可用的和 deisred fd .. 而 dup2 容易出错(正如我猜测的那样..)bcz。它正在覆盖先前存储的 fd 值....
      猜你喜欢
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多