1

Code:

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

Then compile and execute:

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

"test output" not shown when use pipe.

And use ltrace and strace to debug, I got:

$ 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) 
.....

Regarding "test output", the program calls "puts", this is libc library call, but the the kernel "write" did't called. Why ?

fillzero
  • 21
  • 2

1 Answers1

1

After some searching, I found that the problem can be solved by adding 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;
}  

And it works:

test@test-laptop:~/test/1$ ./a.out | tee
test output
Thu Jun 23 18:17:09 CST 2016
hxysayhi
  • 1,888
  • 18
  • 25
fillzero
  • 21
  • 2