Execv Linux printf doesn't work

2020-05-03 13:21发布

I'm trying to run executable using this c code:

  int main(int argc, char *argv[])
  {
     printf("hello.\n");
     sleep(2);
     if (execlp("ls","ls","-l",NULL) == -1)
          printf("Error occured during execute ls.\n");
     return 0;
 }

why printf("hello\n") doesn't work? even if i put sleep?

标签: c linux execv
1条回答
Luminary・发光体
2楼-- · 2020-05-03 13:46

Your program should work when output is to a terminal, but it will not work correctly if output is redirected to a file or a pipe. When stdout is not connected to a terminal, its output is fully buffered. Calling an exec function does not flush the buffer before replacing the current process with the new program, so any buffered output will be lost.

Call fflush(stdout); before calling execlp() and the problem should be resolved. You don't need to sleep, it has no effect on output.

#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
  {
     printf("hello.\n");
     fflush(stdout);
     if (execlp("ls","ls","-l",NULL) == -1)
          printf("Error occured during execute ls.\n");
     return 0;
 }
查看更多
登录 后发表回答