我已经将来自用户的给定命令分成子字符串,这是代码:
int i;
char *line = malloc(BUFFER);
char *origLine = line;
fgets(line, 128, stdin); // get a line from stdin
// get complete diagnostics on the given string
lineData info = runDiagnostics(line);
char command[20];
sscanf(line, "%20s ", command);
line = strchr(line, ' ');
printf("The Command is: %s\n", command);
int currentCount = 0; // number of elements in the line
int *argumentsCount = ¤tCount; // pointer to that
// get the elements separated
char** arguments = separateLineGetElements(line,argumentsCount);
// here we call a method that would execute the commands
if (execvp(*arguments,*argumentsCount) < 0) // execute the command
{
printf("ERROR: exec failed\n");
exit(1);
}
当我在 execvp(*arguments,*argumentsCount)
中执行命令时,它失败了。
怎么了?
谢谢。
编辑:
来自用户的输入是:ls > a.out
,因此我有 3 个字符串,它们是:
ls
、>
、a.out
,但失败了。
最佳答案
如果您不调用 shell,则 Shell 重定向将不起作用。 您也不会通过路径搜索来查找 ls 程序。 一些选项
改用 system(),返回时退出
执行一个 shell 并让它运行你的命令
像 shell 一样设置重定向,然后 fork 并执行每个所需的子程序。
此外,您的命令没有多大意义,您可能想要 ¦ 而不是 >,如果 a.out 不在您的路径中,则可能需要指定它的目录。也考虑给它起一个有意义的名字。
关于c - 在 C 中使用 execvp 执行单独的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10667332/