简体   繁体   English

调用execve()+更改PWD

[英]calling execve() + changing PWD

I want to write a program A which executes another program B . 我想写一个执行另一个程序B的程序A It is very important to execute program B from it's directory, cause it turns on program BB who sits in the same directory of B . 从它的目录执行程序B非常重要,因为它打开了位于B的同一目录中的程序BB

I mean: ./B will work 我的意思是: ./B会起作用

./b/B won't work ./b/B不起作用

I thought about two ways to do so: 我想过两种方法:

  1. do fork() , change the PWD in env, and then call execv() 执行fork() ,更改env中的PWD,然后调用execv()
  2. do fork() , create a temporal variable, envp , and call execve() fork() ,创建时态变量, envp ,并调用execve()

Lets say program A sits here: /home/a , and program B and BB sits here: /home/a/b 让我们说程序A在这里: /home/a ,程序BBB坐在这里: /home/a/b

This is my code of program A who sits in /home/a 这是我在/home/a的程序代码A

#include <iostream>
#include <errno.h>

int main() {

    int pid;
    char *cmd[20] = {"/home/a/b/B", NULL};

    if ((pid = fork()) == 0) {

        /*if (putenv("PWD=/home/a/b") < 0) {
            fprintf(stderr, "error PWD%s\n", strerror(errno));
        }*/

        char *envp[20] = {"PWD=/home/a/b", NULL};

        execve( cmd[0], cmd, envp);

        fprintf(stderr, "error: execv: %s\n", strerror(errno));
        exit(0);
    } else if (pid < 0) {
        fprintf(stderr, "error: fork: %s\n", strerror(errno));
        exit(0);
        }

    fprintf(stderr, "father quits\n");

return 0; 返回0; } }

I tried both of my solutions, but none of them worked, I mean, I manage to execute program B , but it can't find program BB . 我尝试了我的两个解决方案,但是没有一个能够工作,我的意思是,我设法执行程序B ,但它找不到程序BB I also printed program's B 's PWD, and it's /home/a/b/ - but still, it cannot execute BB . 我还打印了程序B的PWD,它是/home/a/b/ - 但是它仍然无法执行BB

Is it possible? 可能吗? Can someone see what I am I do wrong? 有人能看出我做错了吗?

Thanks 谢谢

您正在寻找chdir()而不是envp操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM