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?
Barmar
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;
}
来源:https://stackoverflow.com/questions/37554643/execv-linux-printf-doesnt-work