Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does control return after "execvp()"?

Tags:

c

exit

execvp


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

like image 395
Ajay Garg Avatar asked May 19 '10 06:05

Ajay Garg


2 Answers

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.

like image 123
kennytm Avatar answered Sep 19 '22 20:09

kennytm


The execve() syscall can fail. The classic reason for doing this would be if the file isn't there or isn't executable. execvp() wraps around execve() to add path searching and default environment handling (virtually always what you want!) and so it adds in another few failure modes, notably trying to run something with a simple name that's not on the user's path. In any case, failure is failure and there's not a lot you can do when it happens except report that it has gone wrong and Get the (now useless) child process Out Of Dodge. (The simplest error reporting method is to print an error message, perhaps with perror(), but there are others.)

The reason why you need _exit() as opposed to the more normal exit() is because you want to quit the child process but you do not want to run any registered cleanup code associated with the parent process. OK, a lot of it might be harmless, but doing things like writing goodbye messages to a socket or something would be bad, and it's often not at all obvious what has been registered with atexit(). Let the parent process worry about its resources; the child basically owns nothing other than its stack frame!

like image 44
Donal Fellows Avatar answered Sep 20 '22 20:09

Donal Fellows