0

我是 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);

我认为这里的所有问题都与我分配数组并写入它的指针操作有关。怎么做才对?

4

2 回答 2

2

问题已结束。找到解决方案。棘手的指针声明语法解决了。这是工作的。

谢谢大家。:-|

 void cmdline_to_argv(const char* cmd_line, char ***argv, int* argc){
    int i, spc;
    size_t len;
    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; *argc = 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) { (*argc)++; spc = 0; }
            *d++ = *s;
        }
    }
    (*d++) = '\0'; /* line termination */
    /* calc actual size */
    len = d - cmd_line1;
    /* allocate array of poiters */
    *argv = (char**) malloc(sizeof(char*) * ((*argc)+1) + len);
    (*argv)[*argc] = (char*) NULL;
    d = (char*) &(*argv)[(*argc)+1];
    memmove(d, cmd_line1, len);
    free(cmd_line1);
    cmd_line1 = d;
    /* scan line again to find all lines starts and register */
    for (i=0; i<*argc; i++) {
        (*argv)[i] = d;
        while (*(d++)) ;
    }
}

/* deallocate array and strings */
void free_argv(char ***argv) {
    free(*argv); /* strings laying together at once after pointers array */
}
于 2013-03-05T19:15:42.667 回答
1

你看过这里吗https://www.kernel.org/doc/man-pages/online/pages/man2/getpid.2.html 我相信你想要的是 getpid() 虽然也许你问的更多。

于 2013-03-04T18:50:39.060 回答