c - execvp() 和不完整的多参数命令的问题

标签 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");
}

理想的结果是打印“命令不完整”并且进程结束。

最佳答案

评论中的一个想法完全回答了我的问题(满足我的确切需求)。但不知道如何在这里给予他信任。

解决方案是在使用 execvp() 之前关闭 stdin。如果第一次 scanf 时命令没有完成,程序会抛出错误,这是完美的。 由于我正在运行主程序,因此我在循环中使用它,因此我可以使用 dup 和 dup2 来保存并稍后重新加载标准输入。

我用来测试它是否有效的代码:

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

关于c - execvp() 和不完整的多参数命令的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55315939/

相关文章:

c - 为什么不能将 `char **` 传递给在 C 中采用 `const char **` 的函数?

php - Windows CMD.exe "The system cannot find the path specified."

php 在前台运行另一个脚本

c - 在 C 中提取 dos 命令输出

安卓原生权限和保护级别

c - 如何使用 GDB 在给定函数的范围内声明变量?

c++ - Arduino以太网字节大小问题

在 Windows 中为 tcl/tk starkit 创建 .dll

c - 在 CUDA C 中使用 open() 时出错

c - 如何将包含通配符的路径转换为 ​​C 程序中相应的文件条目?