我正在尝试迭代一些输入(命令和参数),将输入拆分为单独的字符串,然后将该输入传递给 execvp()
。
我遇到了麻烦,因为 execvp()
想要一个 (char*, char*[])
作为它的参数。我正在传递 (char*, char[][])
我认为是同一件事,但它不喜欢它。
我会使用 char*[]
但我不知道在它运行之前字符串有多大,所以这就是我没有使用它的原因。所以很明显,如果我使用 char*[]
,当我尝试访问 char*
的元素时,我会遇到段错误。
这是代码片段
//input
char *line = "echo hello there what is";
int count = 0;
//store arguments
char args[6][10];
int argCount = 0;
//store temp string from input
char temp[100];
int tempCount = 0;
//word(string) size
int wordSize = 0;
/*
Here I iterate over the input, storing each string I find in args
all the above variables help me do that.
*/
execvp(args[0], args);
printf("Error: It didnt work\n");
希望这是一个清晰且有效的问题,如果您想让我添加将输入转换为 args
的代码,请告诉我。
最佳答案
char
数组的数组与指向char
数组的指针数组不同。 execvp()
期望后者以空指针作为其最后一个元素,传递前者具有未定义的行为。
你必须构造一个指针数组,要么从堆中分配,要么用自动存储定义(在堆栈上),用指向参数字符串的指针初始化它,并将这个数组传递给 execvp ()
。
另请注意,echo
既是 shell 内部命令,也是路径中的可执行文件。
这是您相应修改的代码片段(没有解析代码,仍然由您编写):
//input "echo hello there what is";
//arguments array
char *args[6];
/*
* Here you should iterate over the input, storing each string you find
* on the command line into `args` and terminate with a null pointer...
*/
args[0] = "echo";
args[1] = "hello";
args[2] = "there";
args[3] = "what";
args[4] = "is";
args[5] = NULL;
execvp(args[0], args);
关于c - 将 char[][] 传递给 execvp 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55981330/