Wil*_*hes 1 c unix io-redirection
如果我使用puts
,我可以按预期重定向stdout:
#include <stdio.h>
int main() {
char *s = "hello world";
puts(s);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
重定向:
$ gcc -Wall use_puts.c
$ ./a.out
hello world
$ ./a.out > /dev/null
Run Code Online (Sandbox Code Playgroud)
但是,如果我使用write
写入stdout,shell重定向无效:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main() {
char *s = "hello world\n";
write(0, s, strlen(s));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
重定向:
$ gcc -Wall use_puts.c
$ ./a.out
hello world
$ ./a.out > /dev/null
hello world
Run Code Online (Sandbox Code Playgroud)
为什么是这样?在这种情况下,如何将写入重定向到stdout?
你的write
陈述是写给stdin而不是stdout.我很惊讶它的工作原理.
这通常是为什么你应该使用常量而不是文字值,因为它不太容易出现这种错误:
write(STDOUT_FILENO, s, strlen(s));
Run Code Online (Sandbox Code Playgroud)
(STDOUT_FILENO
,STDIN_FILENO
和STDERR_FILENO
定义unistd.h
)