How does one properly use the Unix exec C(++)-command? How does one properly use the Unix exec C(++)-command? unix unix

How does one properly use the Unix exec C(++)-command?


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;}


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