Linux – Echo problems with execv() after fork()

cforklinuxunix

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?

Best Answer

Since your printf("done") gets invoked your execv() clearly failed. All exec() functions do only return if an error occurred. Evaluating errno should help you to find out why it failed.

try using the whole path to echo:

 execv("/bin/echo", earg);

EDIT: if you want to print done as soon as the child exited you should add a wait(NULL) call to your parent. see the manpage of wait() for more information and an example how to use it.

Related Topic