Execve finding paths?

I want to execute a program from my code and provide it with environment variables and arguments. AFAICT, execve is the right choice.

But, execve receives the path argument, not the filename , that is, it expects the first argument to be empty for the executable.

I know I can parse $PATH myself to find the path, but really, is there no other choice? Hasn't anyone realized it somewhere for me?

+4
source share
1 answer

Some systems may provide execvpe() . A Google search for "execvpe" shows many options, including at least one implementation (much more complex than what follows, but it includes most of execvp() in its own code).

For those who do not, you can provide it yourself:

 int execvpe(const char *program, char **argv, char **envp) { char **saved = environ; int rc; environ = envp; rc = execvp(program, argv); environ = saved; return rc; } 

You could probably survive without rc (just forcibly return -1) since execvp() only returns -1 (and it only returns an error).

You probably don't even have to worry about thread safety in this code. The usual script that will use it immediately after fork() , and at this point there is only one thread in the process. If you think you can use it when there are several threads around, then you need to think about whether you can quickly change the global environment. It is clear that if execvp() succeeds, there will be no problems (all threads will abruptly stop). If execvp() fails, then maybe one of the other threads will see the changed environment and may make the wrong decisions based on this. In this case, you need to protect the environment accordingly (and probably include (mutual exclusion) in getenv() , setenv() and putenv() , as well as in execvpe() ).

(The implementation of execvpe() that I found helps avoid thread safety issues by implementing the execvp() logic and then using execve() to execute the program.)

Usually, if execvpe() returns, the process ends, so very often restoring the environment does not affect the program. However, it is better safe than sorry.

+8
source

All Articles