How to use Unix exec C (++) command correctly?

In particular, I need to call the exec version, which maintains the current working directory and sends the standard version to the same terminal as the program that calls exec. I also have a vector of string arguments that I need to pass in some way, and I wonder how I will deal with this. I was told that all this is possible exclusively with fork and exec , and given the terrible lack of documentation on google, I was unable to get the exec part to work.

What exec method am I looking for that can do this, and what should I call it?

+3
source share
3 answers

, char* 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;
}
+4
+1

Google, man, man fork man exec (, , man 2 fork man 3 exec), , .

Debian Ubuntu manpages-dev,

sudo apt-get install manpages-dev
+1

Source: https://habr.com/ru/post/1722939/


All Articles