解析execve()错误的命令行。平原C.

时间:2013-03-04 18:48:10

标签: c pointers segmentation-fault argv

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

我认为这里的所有麻烦都是指针操作,我分配数组并写入它。如何做到正确?

2 个答案:

答案 0 :(得分:2)

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

感谢All。 : - |

 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 */
}

答案 1 :(得分:0)

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