Specifically, I need to call a version of exec that maintains the current working directory and sends standard out to the same terminal as the program calling exec. I also have a vector of string arguments I need to pass somehow, and I'm wondering how I would go about doing all of this. I've been told that all of this is possible exclusively with fork and exec , and given the terrible lack of documentation on the google, I've been unable to get the exec part working.
What exec method am I looking for that can accomplish this, and how do I call it?
If you have a vector of strings then you need to convert it to an array of char*
and call execvp
#include <cstdio>
#include <string>
#include <vector>
#include <sys/wait.h>
#include <unistd.h>
int main() {
using namespace std;
vector<string> args;
args.push_back("Hello");
args.push_back("World");
char **argv = new char*[args.size() + 2];
argv[0] = "echo";
argv[args.size() + 1] = NULL;
for(unsigned int c=0; c<args.size(); c++)
argv[c+1] = (char*)args[c].c_str();
switch (fork()) {
case -1:
perror("fork");
return 1;
case 0:
execvp(argv[0], argv);
// execvp only returns on error
perror("execvp");
return 1;
default:
wait(0);
}
return 0;
}
您可能正在寻找execv()或execvp() 。
You don't necessarily need google to find this out, you should have the man
command available so you can man fork
and man exec
(or maybe man 2 fork
and man 3 exec
) to find out about how the parameters to these system and library functions should be formed.
In Debian and Ubuntu, these man pages are in the manpages-dev
package which can be installed using synaptic or with:
sudo apt-get install manpages-dev
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.