Does control return after "execvp()"?

Ajay Garg picture Ajay Garg · May 19, 2010 · Viewed 9.1k times · Source

if(pid == 0)
{
      execvp(cmd, args);
      // printf("hello"); // apparently, putting this or not does not work.
      _exit(-1);
}
else
{
      // parent process work
}

"execvp()" replaces the current program with the to-be-execed program (of course in the same process context). So, putting, say, any printf() calls after execvp() won't work. That is what the docs say, and I have verified it as well.

But then, why is _exit() needed..? Does it so happen that the control DOES return to statements post execvp() ?

I will be grateful for any pointers.

Thanks

Answer

kennytm picture kennytm · May 19, 2010

The function will return if it has failed.

If one of the exec functions returns to the calling process image, an error has occurred; the return value shall be -1, and errno shall be set to indicate the error.

The _exit() allows terminating the process properly and return an exit code, even if exec fails.