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 anexec
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 callingexeclp()
and the problem should be resolved. You don't need to sleep, it has no effect on output.