linux编程,stdout管道在execve之前不起作用

时间:2016-06-23 10:01:20

标签: c linux pipe execve

代码:

#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
    printf("test output\n");
    execv("/bin/date", argv);
    return 0;
}  

然后编译并执行:

test@test-laptop:~/test/$ ./a.out 
test output
Thu Jun 23 17:44:06 CST 2016

test@test-laptop:~/test/1$ ./a.out | tee
Thu Jun 23 17:44:09 CST 2016
使用烟斗时

“测试输出”未显示

使用ltrace和strace进行调试,我得到了:

$ strace ./a.out  | tee
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb766e000
write(1, "Thu Jun 23 17:48:58 CST 2016\n", 29Thu Jun 23 17:48:58 CST 2016
) = 29
close(1)

$ ltrace ./a.out  | tee
__libc_start_main(0x8048414, 1, 0xbff5fd44, 0x8048470, 0x8048460 <unfinished ...>
puts("test output")                                                                                                                                = 12
execv("/bin/date", 0xbff5fd44 <unfinished ...>
--- Called exec() ---
......
fwrite("Thu", 3, 1, 0xe024e0)                                                                                                                     
strftime(" Jun", 1024, " %b", 0x00e056a0) 
.....

关于“测试输出”,程序调用“puts”,这是libc库调用,但是内核“write”没有被调用。为什么?

1 个答案:

答案 0 :(得分:1)

经过一些搜索,我发现可以通过添加fflush(stdout)

来解决问题
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
    printf("test output\n");
    fflush(stdout);
    execv("/bin/date", argv);
    return 0;
}  

它有效:

test@test-laptop:~/test/1$ ./a.out | tee
test output
Thu Jun 23 18:17:09 CST 2016