我正在使用 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/