繁体   English   中英

从命令行创建 arguments 并保存在数组中

[英]Create arguments from command line and save in an array

我正在尝试从命令行保存我的 arguments 及其参数,如下所示

./run cat hello.txt: grep left: wc -c

我想在不知道数量的情况下将数组中的每个参数分开如下:

char *cat_args[] = {"cat", "tests/nevermind", NULL};
char *grep_args[] = {"grep", "left", NULL};
char *cut_args[] = {"wc", "-c", NULL};

我怎样才能做到这一点?

int nbProc = 2;
for (int i = 0; i < argc; i++){
        if (strcmp(argv[i], ":") == 0){
            nbProc++;
        }
    }

int indice_debut[nbProc-2];
int j = 0;
for (int i = 1; i < argc; i++){
        if (strcmp(argv[i], ":") == 0){
            argv[i] = NULL;
            indice_debut[j] = i + 1;
            j++;
        }
    }

有了这个,我可以得到indice_debut = {4,7}因为有:在第 4 和第 7 position。

我试图这样运行它,但没有运气,我这样做是为了可以使用execvp

execvp(argv[indice_debut[0]], argv + indice_debut[0]);

谢谢

使用malloc()动态分配指针数组。 最多可以有argc/2命令,因为最坏的情况是交替word: word: word: ... ,所以分配那么多元素。 数组元素可以指向argv的元素,您可以将:参数替换为 null 指针以结束每个子命令。

int main(int argc, char **argv) {
    if (argc < 2) {
        printf("At least one command is required\n");
        exit(1);
    }

    char **arg_arrays = malloc(argc/2 * sizeof *arg_arrays);
    int array_index = 0;
    int arg_index = 0;
    while (arg_index < argc) {
        arg_arrays[array_index++] = &argv[arg_index];
        for (; arg_index < argc && strcmp(argv[arg_index], ":") != 0; arg_index++) {}
        argv[arg_index] = NULL;
    }

    // Execute each of the subcommands
    for (int i = 0; i < array_index; i++) {
        pid_t pid = fork();
        if (pid == 0) {
            execvp(arg_arrays[i][0], arg_arrays[i]);
        } else if (pid < 0) {
            perror("fork");
            exit(1);
        }
    }
    // wait for all the subcommands to finish
    while (wait(NULL) > 0) {}
}

这只是一个如何解析子命令并执行它们的简单示例。 如果您想将 pipe 从一个命令转移到下一个命令,则需要添加该代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM