简体   繁体   中英

Echo problems with execv() after fork()

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?

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.

execv will not search for echo command in the PATH, so it fails, and it prints out "done" (which should not happen if execv is successful). You must supply the full path for execv to work

You may want to use execvp instead. It will search for the echo command in the PATH variable.

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