AFAICS, the child process inherits stdout/stdin from the parent process on fork(). This leaves me wondering why the following code does NOT work:
int main(int argc, char *argv[])
{
char *earg[] = {"echo", "Hello", NULL};
if(fork() == 0) {
printf("running echo...\n");
execv("echo", earg);
printf("done!\n");
exit(0);
} else {
sleep(2);
}
return 0;
}
When running this little program, the two printf() calls appear just fine on the console. But the call to echo somehow gets lost! The output on the console is just:
running echo...
done!
Can somebody explain to me why the echo output doesn’t appear on the console? And how I can fix this?
execvwill not search forechocommand in the PATH, so it fails, and it prints out"done"(which should not happen ifexecvis successful). You must supply the full path forexecvto workYou may want to use
execvpinstead. It will search for theechocommand in the PATH variable.