Creating a multi-level pipe for Linux commands

早过忘川 提交于 2020-01-25 08:03:14

问题


I'm trying to create a multi-level pipe, where the input is Linux commands (e.g. ls | sort) and the output is just the regular output when typed into a Linux console (essentially just use execlp to execute the commands).

I've attempted to create a program that works for 1 and 2 levels, but I can't seem to get the 2 level one to work, specifically with the command "ls | sort". The program just freezes. I also don't know how to continue beyond that and add more levels (required to support 16 total).

// the function has to return unless the command is "exit"
void process_cmd(char *cmdline) {
    // exit program
    if (strcmp(cmdline, "exit") == 0) {
        printf("The shell program (pid=%d) terminates\n", getpid());
        exit(0);
    }

    // separate the user input into the different commands using another 
    // defined function
    char* strings[MAX_PIPE_SEGMENTS];
    int x = 0;
    int* numTokens = &x;
    tokenize(strings, cmdline, numTokens, "|");

    // 1 command
    if (*numTokens == 1) {
        pid_t pid = fork();
        if (pid == 0) {
            execlp(strings[0], strings[0], NULL);
        } else {
            wait(0);
            return;
        }
    }

    // 2 commands, this is the problem
    int ps[*numTokens];
    pipe(ps);
    pid_t pid = fork();
    if (pid == 0) {
        pid_t pid2 = fork();
        if (pid2 == 0) {
            close(1);
            dup2(ps[1], 1);
            close(ps[0]);
            execlp(strings[0], strings[0], NULL);
        } else {
            close(0);
            dup2(ps[0], 0);
            close(ps[1]);
            wait(0);
            execlp(strings[1], strings[1], NULL);
        }
    } else {
        wait(0);
        return;
    }
}

来源:https://stackoverflow.com/questions/58374595/creating-a-multi-level-pipe-for-linux-commands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!