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

前端 未结 1 792
予麋鹿
予麋鹿 2021-01-12 14:34

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

For example, can freopen(\"/dev/n

相关标签:
1条回答
  • 2021-01-12 15:19

    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.

    0 讨论(0)
提交回复
热议问题