如何以编程方式更改进程的执行路径?

发布于 2024-12-17 10:36:24 字数 313 浏览 0 评论 0原文

我正在开发一个迷你 shell,并尝试动态设置执行路径。 我使用 setvar() 来设置 PATH,当我使用 getvar() 检查它时,它会读取新的 PATH。 这是我尝试执行的两件事:
1.我将PATH更改为/bin,我知道它包含了大部分系统功能,但没有程序可以运行。我还可以验证环境中是否已设置路径。我使用 execvp()
执行命令 2. 然后我使用 extern char** environ 获取环境并将其传递给 execvpe() 但它仍然不起作用。

I am working on a mini-shell, and am trying to set the execution path dynamically.
I am using setvar() to set the PATH and when I check it with getvar() it reads the new PATH.
Here are the two things I tried to execute:
1. I change the PATH to /bin which I know contains most system functions, but no programs can work. I can also verify that the path has been set in the environment. I execute the commands using execvp()
2. I then used extern char** environ to get the environment and pass it into execvpe() but it still doesn't work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不醒的梦 2024-12-24 10:36:24

我通过使用 istringstream 手动搜索 PATH 然后使用它来执行该过程解决了这个问题:

string dir;
string path = get_var("PATH");
istringstream search(path);
while(search.good()) {
    getline(search, dir, ':');
    if(dir != "") {
        struct stat st;
        if(dir[dir.length()] != '/') dir.append("/");
        string file = dir + cmdArg[0];
        //is file in dir?
        if(stat(file.c_str(), &st) == 0) {
            execvp(file.c_str(), cmdArg);
        }
    }
}

I solved this by using istringstream to manually search the PATH and then use that to execute the process:

string dir;
string path = get_var("PATH");
istringstream search(path);
while(search.good()) {
    getline(search, dir, ':');
    if(dir != "") {
        struct stat st;
        if(dir[dir.length()] != '/') dir.append("/");
        string file = dir + cmdArg[0];
        //is file in dir?
        if(stat(file.c_str(), &st) == 0) {
            execvp(file.c_str(), cmdArg);
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文