【问题标题】:How to execute arbitrary pipes in c and continue如何在c中执行任意管道并继续
【发布时间】:2013-01-10 01:30:28
【问题描述】:

我正在尝试分叉,然后在子进程中执行两个或多个管道命令。我的想法是使用 while 循环在一个进程中连续分叉并执行命令,同时在另一个进程中继续循环。这是我的代码:

void
execute_pipe_command(command_t *c)
{
    command_t command = *c;
    pid_t pid = fork();
    if(pid > 0) {
        int status;
        while(waitpid(pid, &status, 0) < 0)
            continue;
        if(!WIFEXITED(status))
            error(1, errno, "Child exit error");
        command->status = WEXITSTATUS(status);
        return;
    } else if (pid == 0) {
        while(command->type == PIPE_COMMAND)
        {
            int fd[2]; pipe(fd);
            pid = fork();
            if(pid > 0) {
                close(fd[0]);
                dup2(fd[1], STDOUT_FILENO);
                char **args = command->u.command[1]->u.word;
                execvp(args[0], args);
            } else if (pid == 0) {
                close(fd[1]);
                dup2(fd[0], STDIN_FILENO);
                command = command->u.command[0];
                continue;
            } else {
                error(1, errno, "forking error");
            }
        }
        char **args = command->u.word;
        execvp(args[0], args);
    } else {
        error(1, errno, "forking error");
    }
}

Command 是一个保存它的类型的结构,如果它是一个管道命令,它保存左右子命令。否则,如果它是一个简单的命令,它包含一个组成命令的字符串数组。

当我用像ls | cat 这样的管道命令调用这个函数时,它应该执行命令,但它的行为却很奇怪。前两个管道命令将运行,但不会将控制权交还给程序。相反,它会挂起。随后的命令将被忽略。所以如果我给这个ls | cat | wc 这个函数将打印 ls 并且在我给一个 SIGINT 之前不会退出。

我对发生的事情感到非常困惑。如果有人能指出问题,我将不胜感激。

【问题讨论】:

  • 如果颠倒纬度不是吗?我猜父母应该转移到下一个命令,孩子执行 exec ......对吗?

标签: c exec fork pipe gnu


【解决方案1】:

while (command-&gt;type == PIPE_COMMAND) 总是正确的!这是挂起的方式。

【讨论】:

    猜你喜欢
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2016-10-25
    相关资源
    最近更新 更多