execve with path search?

你说的曾经没有我的故事 提交于 2019-12-05 16:10:32

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

For those that do not, you can provide it for 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 probably could survive without rc (just forcibly returning -1) since execvp() only ever returns -1 (and it only ever returns on an error).

You probably do not even have to worry about thread safety in this code. The normal scenario that will use it is just after a fork(), and at that point, there is only one thread in the process. If you think you may use it when there are multiple threads around, then you need to think rather carefully about whether it is safe to modify the global environment even briefly. Clearly, if the execvp() succeeds, there won't be a problem (all the threads will be abruptly terminated). If the execvp() fails, then maybe one of the other threads would see the modified environment and might make bad decisions based on that. In which case, you would need to protect the environment appropriately (and that probably involves (mutual exclusion) locking in getenv(), setenv() and putenv() as well as in execvpe()).

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

Normally, if execvpe() returns, the process will exit, so very often reinstating the environment is not going to affect the program. However, it is better safe than sorry.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!