1

代码:

#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”没有调用。为什么 ?

4

1 回答 1

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
于 2016-06-23T10:18:29.977 回答