首页 > 解决方案 > 为 Linux 命令创建多级管道

问题描述

我正在尝试创建一个多级管道,其中输入是 Linux 命令(例如 ls | sort),输出只是输入到 Linux 控制台时的常规输出(基本上只是使用 execlp 来执行命令)。

我试图创建一个适用于 1 级和 2 级的程序,但我似乎无法让 2 级工作,特别是使用命令“ls | sort”。该程序只是冻结。我也不知道如何继续并添加更多级别(总共需要支持 16 个级别)。

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

标签: cunixcommand-linepipe

解决方案


推荐阅读