C 中的自定义管道实现 - 无法获得正确的状态

问题描述 投票:0回答:0

我实现了一个用于执行多个管道的递归

void handlePipes(int pipeIndex, int IOIndex, int fdprev) {
    char *commandArr[10];
    breakCommand(commandArr, splitCommands[numOfExec++], " ");
    CLOSEME(fds[1]);
    if (pipe(fds) == -1) {
        printf("Error creating pipe.\n");
        exit(1);
    }
    if (IOIndex < numOfPipes) {
        int pid = fork();
        if (pid == 0) {
            handlePipes(pipeIndex - 1, IOIndex + 1, fds[0]);
        }
    }

    if (fdprev >= 0) {
        if (dup2(fdprev, STDIN_FILENO) == -1) {
            printf("Error redirecting standard input.\n");
            exit(1);
        }
        CLOSEME(fds[0]);
        CLOSEME(fdprev);
    }

    if (IOIndex != numOfPipes && fds[1] > 0) {
        if (dup2(fds[1], STDOUT_FILENO) == -1) {
            printf("Error redirecting standard output.\n");
            exit(1);
        }
        CLOSEME(fds[0]);
    }
    CLOSEME(fds[1]);
    if (pipeIndex == 0) {
        handleIfFilePipe(pipeIndex);
        handleSwitchCasePipe();
    }
    deleteIf(commandArr);

    if (execvp(commandArr[0], commandArr) == -1) {
        printf("Error executing command.\n");
        exit(1);

    }
}

上面的函数在分叉的孩子中执行,如下所示:

int pipeIndex = numOfPipes;
handlePipes(pipeIndex, 0, -1);

管道索引变量用于确定我是否处于管道的最后一个命令,这有助于模仿

ls | grep s > file.txt

的行为

当我执行以下命令时:

date | grep Test

我得到的状态码是 0,但是当我在我的 shell 上执行它时,我得到状态码 1 知道为什么状态没有被正确传播吗?

c pipe fork status
© www.soinside.com 2019 - 2024. All rights reserved.