简体   繁体   中英

Execv Linux printf doesn't work

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?

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;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM