[英]execve(…) does not execute program despite passing in PATH variable
I'm executing a simple shell program from the directory: 我正在从目录中执行一个简单的shell程序:
/home/user/shell.exe /home/user/shell.exe
Using the code below, I'm able to run files that are in the same folder as my shell executable, but am unable to run programs such as ls.exe. 使用下面的代码,我能够运行与我的shell可执行文件位于同一文件夹中的文件,但是无法运行ls.exe等程序。
The tokens container includes the file name as the first element and any subsequent tokens (such as "-l" in the input "ls.exe -l") in the following elements. 标记容器包括作为第一个元素的文件名和以下元素中的任何后续标记(例如输入“ls.exe -l”中的“-l”)。
if (fork())
{
int status;
wait(&status);
}
else
{
std::vector<const char*> exeArgs;
std::vector<const char*> envArgs;
std::for_each(tokens.begin(), tokens.end(),
[&exeArgs](const string& elem){ exeArgs.push_back(elem.c_str()); }
);
exeArgs.push_back(nullptr);
string path = "PATH=";
path.append(getenv("PATH"));
envArgs.push_back(path.c_str());
envArgs.push_back(nullptr);
if (execve(exeArgs[0], const_cast<char *const *>(&exeArgs[0]),
const_cast<char *const *>(&envArgs[0])))
{
std::cout << word << ": command not found" << std::endl;
exit(0);
}
}
I've spent countless hours just googling and reading the man pages over and over but can't seem to get a clue why this code doesn't work. 我花了无数个小时只是谷歌搜索和一遍又一遍地阅读手册页但似乎无法弄清楚为什么这段代码不起作用。
The idea is that my shell program should allow users to set the PATH variable and then execute programs with that PATH variable, which is why I have to make execve() work properly instead of just using execvp(). 我的想法是我的shell程序应该允许用户设置PATH变量然后用该PATH变量执行程序,这就是为什么我必须使execve()正常工作而不是仅使用execvp()。
I have a map of shell variables in a separate part of the file but since I can't even get this to work, I thought it would be pointless to include that. 我在文件的一个单独部分有一个shell变量的映射,但由于我甚至无法使它工作,我认为包含它是没有意义的。
You do know that the exec
family of functions replaces the current process with the image of the new program? 你知道
exec
系列函数替换当前的进程与新节目的形象? That's why it's so common to use fork
before exec
. 这就是为什么在
exec
之前使用fork
是如此常见。
Armed with that knowledge, it's easy to find a solution for you, and how you can use execvp
(which you need to use, execve
doesn't really use the environment you pass, it just passes it along to the new program): You fork
and use setenv
to set the PATH
of the new process, before calling execvp
. 与知识的武装,很容易找到一个解决方案适合你,你可以如何使用
execvp
(你需要使用, execve
并没有真正使用你传递的环境,它只是将它传递给新程序):您fork
并使用setenv
在调用execvp
之前设置新进程的PATH
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.