所以我有以下 C 代码,要求用户给出一个命令(在 unix 中有效),然后我必须获取该字符串并将其拆分为一个数组,以便执行用户使用 execvp 给出的命令()。它可以编译,但 execvp 似乎不起作用。我在数组中分割用户输入的方式有问题吗? PS:有些内容不是必需的,但这不是最终的程序。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
main() {
char str[64];
int i =0;
char *p = strtok(str," ");
printf("Please give me a Unix command! :\n");
gets(str);
char *array[sizeof(str)];
while (p!=NULL) {
array[i++] = p;
p = strtok (NULL, " ");
}
execvp(str ,array);
perror("execvp");
}
运行时得到的输出是:
Please give me a Unix command! :
ls -l
execvp: No such file or directory
最佳答案
您在 str
获得任何信息之前调用 strtok(str, "")
。
在获得输入后简单地调用它:
main() {
char str[64];
char *array[sizeof(str)];
char *p = NULL;
int i = 0;
printf("Please give me a Unix command! :\n");
fgets(str, sizeof(str), stdin); // Use fgets instead of gets.
p = strtok(str," ");
while (p != NULL) {
array[i++] = p;
p = strtok(NULL, " ");
}
execvp(str, array);
}
关于c - 获取用户输入,然后执行 execvp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41639210/