I want to write a program A
which executes another program B
. 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
.
I mean: ./B
will work
./b/B
won't work
I thought about two ways to do so:
fork()
, change the PWD in env, and then call execv()
fork()
, create a temporal variable, envp
, and call execve()
Lets say program A
sits here: /home/a
, and program B
and BB
sits here: /home/a/b
This is my code of program A
who sits in /home/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; }
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
. I also printed program's B
's PWD, and it's /home/a/b/
- but still, it cannot execute BB
.
Is it possible? Can someone see what I am I do wrong?
Thanks
您正在寻找chdir()
而不是envp
操作。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.