I have noticed some unexpected behaviour on both OS X and Linux. Turning on non-blocking I/O (using O_NONBLOCK
) for standard output turns it on for standard input too!
Are these OSes behaving correctly? If so, is this behaviour defined by POSIX? Please point me to the relevant documentation if this is the case.
Here's a example program I used to test this:
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
int flags = fcntl(STDOUT_FILENO, F_GETFL);
if (argc > 1 && strcmp(argv[1], "1") == 0) {
fcntl(STDOUT_FILENO, F_SETFL, flags | O_NONBLOCK);
}
printf("stdout O_NONBLOCK is: %d
", fcntl(STDOUT_FILENO, F_GETFL) & O_NONBLOCK);
printf("stdin O_NONBLOCK is: %d
", fcntl(STDIN_FILENO, F_GETFL) & O_NONBLOCK);
return 0;
}
On OS X:
$ clang -o fd-test fd-test.c
$ ./fd-test
stdout O_NONBLOCK is: 0
stdin O_NONBLOCK is: 0
$ ./fd-test 1
stdout O_NONBLOCK is: 4
stdin O_NONBLOCK is: 4
On Linux:
$ gcc -o fd-test fd-test.c
$ ./fd-test
stdout O_NONBLOCK is: 0
stdin O_NONBLOCK is: 0
$ ./fd-test 1
stdout O_NONBLOCK is: 2048
stdin O_NONBLOCK is: 2048
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…