Does control return after "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 program that will be executed (of course, in the same process context). So, if, say, any calls to printf () after execvp () will not work. This is what the docs say, and I also checked it.

But then why is _exit () necessary ...? Does it happen that the control returns to post exec () statements?

I would be grateful for any pointers.

thanks

+4
source share
4 answers

The function will return if it failed.

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

_exit() allows you to correctly terminate the process and return the exit code, even if exec failed.

+6
source

If execvp fails, _exit will be called.

execvp man page says:

Return value
If any of the exec () functions returns, an error will occur. The return value is -1, and the errno global variable will be set to indicate an error.

+1
source

A call to execve() may fail. A classic reason for this would be if the file is missing or not executable. execvp() goes around execve() to add default path searching and default processing (almost always what you want!), and therefore it adds some more failure modes, especially trying to run something with a simple name that not in the user's path. In any case, a failure is a failure, and you cannot do much when it happens, except to report that it went wrong and get the (now useless) Out Of Dodge child process. (The easiest way to report errors is to print an error message, possibly with perror() , but there are others.)

The reason you need _exit() , as opposed to the more usual exit() , is because you want to exit the child process, but do not want to run any registered cleanup code associated with the parent process. Well, many of them can be harmless, but to do something like writing farewell messages to a socket, or something would be bad, and it is often not quite obvious what was registered in atexit() . Let the parent process worry about its resources; the child basically has nothing but his stack frame!

+1
source

It should be noted that you generally do not want the completion status of the process to be signed (if portability is important). While exec() may return -1 on failure, returning it means that you can handle this failure in child code.

The actual status of _exit() for the child should be 0 - 255, depending on what errno was created.

0
source

Source: https://habr.com/ru/post/1310200/


All Articles