如何正确使用Unix exec C(++)命令? [英] How does one properly use the Unix exec C(++)-command?

查看:85
本文介绍了如何正确使用Unix exec C(++)命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具体来说,我需要调用一个exec版本,该版本维护当前的工作目录,并将标准发送到与调用exec的程序相同的终端.我还有一个向量字符串参数,我需要以某种方式传递它,我想知道如何进行所有这些操作.有人告诉我,所有这些都只能通过 fork and exec 来实现,并且由于google上缺乏文档的严重限制,我无法使exec部分正常工作.

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.

我正在寻找可以实现此目标的exec方法,怎么称呼它?

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

推荐答案

如果您有字符串向量,则需要将其转换为char*数组并调用

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

这篇关于如何正确使用Unix exec C(++)命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆