我正在尝试弄清楚如何将get_arguments
到NULL
的字符串数组终止,或者如果这不是我execv
调用中的问题。< / p>
char ** get_arguments(const char * string) {
char * copy = strdup(string);
char * remove_newline = "";
for(;;) {
remove_newline = strpbrk(copy, "\n\t");
if (remove_newline) {
strcpy(remove_newline, "");
}
else {
break;
}
}
char (* temp)[16] = (char *) malloc(256 * sizeof(char));
char * token = strtok(copy, " ");
strcpy(temp[0], token);
int i = 1;
while (token && (token = strtok(NULL, " "))) {
strcpy(temp[i], token);
i++;
}
char * new_null;
//new_null = NULL;
//strcpy(temp[i], new_null);
if(!temp[i]) printf("yup\n");
int c = 0;
for ( ; c <= i; c++) {
printf("%s ", temp[c]);
}
return temp;
}
我正在尝试读取字符串,空格分隔,类似于find ./ -name *.h
。我正在尝试将它们输入execv
。
char (* arguments)[16] = (char **) malloc(256 * sizeof(char));
// ...多行不相关的代码
pid = fork();
if (pid == 0) {
arguments = get_arguments(input_string);
char * para[] = {"find", "./","-name", "*.h", NULL};
execv("/usr/bin/find", (char * const *) arguments);
//printf("%s\n", arguments[0]);
printf("\nexec failed: %s\n", strerror(errno)); //ls -l -R
exit(-1);
}
当我arguments
execv
para
来电arguments
时,它按预期工作,但尝试与exec failed: Bad address
通话时会返回NULL
。如果我从para
删除strcpy(temp, (char *) NULL)
,我会遇到同样的问题。我已尝试get_arguments
,您在Segmentation fault
中看到的版本以及其他一些我无法完全回忆起来的内容,我的计划范围从strcpy
到无法从尝试char ** arguments = (char *) malloc(256 * sizeof(char));
NULL编译。
将参数和temp的声明更改为clears up
``char ** temp =(char *)malloc(256 * sizeof(char)); but causes segfault on all calls to
警告:从不兼容的指针类型初始化{ {1}} get_arguments`。
答案 0 :(得分:1)
你想要这个:
char* temp[256]; // an array of 256 char*'s
char * token = strtok(copy, " ");
temp[0] = strdup(token);
int i = 1;
while (token && (token = strtok(NULL, " "))) {
temp[i] = strdup(token);
i++;
}
temp[i] = NULL;