views:

212

answers:

3

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?

+1  A: 

You may be looking for execv() or execvp().

Tim
+4  A: 

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;
}
Eli Courtwright
Don't forget to put a NULL at the end of that argv!
Suppressingfire
Don't forget to call c_str().
Martin York
Thanks, the code I posted was filled while I hammered out a complete working example.
Eli Courtwright
Use a vector<char const*> instead of new[] here, and do that after forking.
Roger Pate
I feel like there's a good stl way to do the vector -> char *[] conversion.
Stefan Kendall
+2  A: 

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
Suppressingfire
Ubuntu 9.10. man fork, man exec, nothing.
Stefan Kendall
`sudo apt-get install manpages-dev`
Roger Pate
I feel that should be part of the answer, considering it's not obvious where to get the extra manpages from, if one is used to delightful, rich web documentation.
Stefan Kendall
+1 for the edit.
Stefan Kendall