我是 C 指针的新手,并试图用命令行执行进程并获取它的 pid。任何使用命令行的 system()、sh() 等都不会返回 pid,所以我决定使用 execve()。但它需要将命令行解析为字符串数组。
我找到了一些现有的解决方案,但我无法使任何工作。所以,我自己写了。它在我的测试程序中有效,但在实际程序中会导致分段错误。谁能告诉我,我错在哪里?代码是:
void cmdline_to_argv(const char* cmd_line, char*** argv, int* argc){
int len, i, count, spc;
char *s,*d;
/* make a copy to play with */
char *cmd_line1 = strdup(cmd_line);
/* count items to deal with and trim multiple spaces */
d = s = cmd_line1; spc = 1; count = 0; len=strlen(cmd_line1);
for (i=0; i<len;i++,s++) {
switch (*s) {
case ' ':
if (spc) continue;
*d++ = '\0'; /* replace spaces with zeroes */
spc = 1;
break;
default:
if (spc) { count++; spc = 0; }
*d++ = *s;
}
}
(*d++) = '\0'; /* line termination */
/* reallocate copy to correct size */
cmd_line1 = realloc( cmd_line1, d - cmd_line1);
/* allocate array of poiters */
*argv = (char**) malloc(sizeof(char*) * (count+1));
argv[count] = NULL;
/* scan line again to find all lines starts and register */
s = cmd_line1;
for (i=0; i<count; i++) {
(*argv)[i] = s;
while (*(s++)) ;
}
*argc = count;
}
这就是我所说的:
char **chargv = NULL;
int chargc;
/* parse line to argument array */
cmdline_to_argv(cmdline, &chargv, &chargc);
我认为这里的所有问题都与我分配数组并写入它的指针操作有关。怎么做才对?