Using execv to do basic I/O

风流意气都作罢 提交于 2021-02-11 18:10:45

问题


I'm trying to use execv() to allow me to read into an output file, outputfile.txt, from the terminal. The problem I'm having is that it won't work at all and I don't know if I'm using it correctly.

My code so far:

void my_shell() {
    char* args[2];
    args[0] = "/usr/bin/tee";
    args[1] = "outputfile.txt";
    execv(args[0], &args[0]);   
}

int main() {

    cout << "%";
    //string input;
    pid_t pid, waitPID;
    int status = 0;
    pid = fork();
    if (pid == 0) {
        my_shell();
    }
    else if (pid < 0) {
        cout << "Unable to fork" << endl;
        exit(-1);
    }

    while ((waitPID = wait(&status)) > 0) {
    }

    return 0;
}

What it's doing right now is that nothing is happening at all. The program forks fine, but what's in my_shell isn't doing anything at all. What am I doing wrong?


回答1:


You're missing the NULL terminator to args.

void my_shell() {
    char* args[3];
    args[0] = "/usr/bin/tee";
    args[1] = "outputfile.txt";
    args[2] = NULL;
    execv(args[0], args);   
}


来源:https://stackoverflow.com/questions/21618609/using-execv-to-do-basic-i-o

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!