首页 > 解决方案 > 用叉子处理几个管道

问题描述

我必须做一个非常简单的 shell,它接受一个命令作为参数,例如:

./a.out "/bin/ls" "|" "/usr/bin/grep/" "m" "|" "/usr/bin/grep" "u"

该命令将始终有效(没有语法错误),我只需要处理管道。我已经有我的 ast 工作,但我在执行部分有问题。这是我的 ast 结构:

struct      s_ast
{
    int     t;   // type (either PIPE or CMD)
    t_ast   *l;  // left node (or NULL it t == CMD)
    t_ast   *r;  // right node (or NULL it t == CMD)
    char    **c; // the command with its args (or NULL if t == PIPE)
};

这是执行部分的代码:

void exe_pipe(t_ast *ast, char **env)
{
    int fd[2], pid = 0;

    if (pipe(fd) < 0 || (pid = fork()) < 0)
    {
        error(NULL, NULL);
    }
    if (pid == 0)
    {
        dup2(fd[1], STDOUT_FILENO);
        close(fd[0]);
        close(fd[1]);
        exe(ast->l, env);
        exit(0);
    }
    // EDIT: I don't fork anymore for the right side of a PIPE node
    dup2(fd[0], STDIN_FILENO);
    close(fd[1]);
    close(fd[0]);
    exe(ast->r, env);
    waitpid(pid, NULL, 0);
}

它运行良好,对于每个简单的命令,我都会得到预期的结果,但是如果我给出一个带有很多管道的大命令,我会得到Error: fork error消息。为了测试它,我曾经ulimit -Su 300减少了同时运行的最大授权进程数,并且我向程序传递了一个带有一百个管道的命令。

我尝试了几件事,但我不知道如何输入管道数量超过允许的最大进程数的命令。

标签: cprocesspipefork

解决方案


推荐阅读