Is it possible that `fileno(stdout) != 1` on a POSIX system?

南笙酒味 提交于 2019-12-19 06:44:09

问题


Can stdout file descriptor differ from 1 (STDOUT_FILENO) assuming stdout need not be a modifiable lvalue?

For example, can freopen("/dev/null", "w", stdout) change fileno(stdout) result?


回答1:


Yes.

Test program:

#include <stdio.h>

int main() {
    fclose(stdin);
    freopen("stdout.txt", "w+", stdout);
    fprintf(stderr, "%d\n", fileno(stdout));
    return 0;
}

This prints 0 on my machine (OS X 10.9.4).

File descriptors are typically reused starting from the lowest number first. By closing stdin, file descriptor 0 is freed up, and the subsequent freopen will use file descriptor 0 when opening the file.



来源:https://stackoverflow.com/questions/25516375/is-it-possible-that-filenostdout-1-on-a-posix-system

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!