execvp()和不完整的多参数命令存在问题

时间:2019-03-23 16:34:11

标签: c exec system-calls

我正在使用execvp()运行一些系统调用。程序对于有效的命令非常有用,而对于不存在的任何命令都会失败,这是完美的。 该程序是,当我在需要额外参数(例如cat)的命令上使用execvp()而我不提供参数时,该程序只是从输入中无限读取。

我不确定如何解决此问题,因为如果命令不完整,我不知道如何“告诉”。有什么想法吗?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
        char command[1000];


        printf("Enter command: ");
        scanf("%[^\n]s", command);

        char *temp = strtok(command, " ");
        char *commandList[100];
        int index = 0;

        while (temp != NULL) {
                commandList[index] = temp;
                index++;

                temp = strtok(NULL, " ");
        }

        commandList[index] = NULL;

        execvp(commandList[0], commandList);

        printf("Failed");
}

理想的结果是打印出“命令未完成”并且过程结束。

1 个答案:

答案 0 :(得分:0)

评论中的一个想法完全回答了我的问题(根据我的确切需求)。不过,不知道如何在此赞扬他。

解决方案是在使用execvp()之前直接关闭stdin。如果命令在第一个scanf上未完成,则程序将引发错误,这是完美的。 由于我正在循环运行主程序,因此可以在以后使用dup和dup2保存并重新加载stdin。

我用来测试它是否可以工作的代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
        char command[1000];

        int stdinput = dup(STDIN_FILENO);

        close(STDIN_FILENO);

        dup2(stdinput, STDIN_FILENO);


        printf("Enter command: ");
        scanf("%[^\n]s", command);


        printf("%s\n", command);
}