在C语言中实现管道时出现了错误的文件描述符问题

4

我正在尝试实现一个样例程序,类似于一个执行命令"ls | wc"的shell。

使用管道来实现该命令。当我执行这个命令时,我收到以下错误:

wc:标准输入:坏文件描述符 0 0 0 wc:-:坏文件描述符

请检查代码并提供反馈。注意: 1)解析是一个库,它接受输入并将每个命令作为带有参数和必要数据的链表返回。解析工作正常。 2)我在不同的子进程中执行每个命令,因此需要进行fork。

#include <stdio.h>
#include <stdlib.h>
#include "parse.h"

int pip[3][2];
int main(int argc, char *argv[], char *envp[])
{
    Pipe p; 
    Cmd c;
    pipe(pip[0]);
    pipe(pip[1]);   
    pid_t pid;
    pid=fork();
    char *host = "armadillo";
    printf("%s%% ", host);
    p = parse();
    c=p->head;  
    printf("1 \n");
    pid=fork();

    if(pid==0)
    {
        close(pip[0][0]);
        close(STDOUT_FILENO);
        dup2(pip[0][1],STDOUT_FILENO);
        execvp(c->args[0],c->args);
    }
    else
    {
        waitpid(pid,NULL,0);
    }
    printf("2 \n");

    close(pip[0][1]);
    close(pip[0][0]);

    c=c->next;
    printf("%s \n",c->args[0]);
    pid=fork();
    if(pid==0)
    {
        close(STDIN_FILENO);
        dup2(pip[0][0],STDIN_FILENO);
        close(pip[0][1]);
        execvp(c->args[0],c->args);
    }
    else
    {   
        waitpid(pid,NULL,0);
        close(pip[0][1]);
        close(pip[0][0]);
    }

}

1
你为什么要进行两次分叉?我的意思是,在你实际执行任何操作之前,你为什么要进行那个“分叉”调用呢? - Some programmer dude
@JoachimPileborg 我正在使用不同的子进程来执行每个命令,因此ls和wc各有一个分支。 - Kai
小心关闭管道描述符的位置。此外,管道中的进程必须能够同时运行;如果在启动第二个进程之前等待第一个进程完成,则可能会写入超出管道容量的数据,因此它会阻塞等待第二个进程从管道中读取,但第二个进程直到第一个进程完成后才会启动,因此很长一段时间内什么都不会发生。 - Jonathan Leffler
管道的两端必须同时打开,否则写入管道的操作将会失败。 - user3629249
为什么会打开多个管道? - user3629249
3个回答

7
一个主要问题在这里:
close(pip[0][1]);
close(pip[0][0]);

...

dup2(pip[0][0],STDIN_FILENO);
close(pip[0][1]);

在这里,您首先关闭文件描述符,然后程序稍后尝试再次使用它们。


1
但是如果我注释掉关闭语句,程序就不会结束,我也看不到任何输出。 - Kai

1
您的代码存在一些问题:


你正在创建初始进程的子进程。
pid=fork();
char *host = "armadillo";
printf("%s%% ", host);
p = parse();
c=p->head;  
printf("1 \n");
pid=fork(); // this fork here is wrong

你正在进行分叉,然后再次分叉,以便父进程创建一个子进程,然后两个进程各自创建一个子进程。此时您已经有了4个进程
在这部分中,您的代码可能类似于以下内容:
pid_t pid;
pid=fork();
char *host = "armadillo";
printf("%s%% ", host);
p = parse();
c=p->head;  
printf("1 \n");
// pid=fork(); // it'll be in another part

if (pid == -1) {
    // print error
    exit(1);
} else if (pid == 0) {
    //child
    close(pip[0][0]);
    close(STDOUT_FILENO);
    dup2(pip[0][1],STDOUT_FILENO);
    close(pip[0][1]); // I added this
    execvp(c->args[0],c->args);
}
//parent
waitpid(pid,NULL,0); // it's not a good idea but I leave it here
printf("2 \n");

// now you can fork again and use the same pid variable
pid=fork();

你正在等待孩子完成。

if(pid==0)
{
    close(pip[0][0]);
    close(STDOUT_FILENO);
    dup2(pip[0][1],STDOUT_FILENO);
    execvp(c->args[0],c->args);
}
else
{
    waitpid(pid,NULL,0); // you have more commands to execute yet, so you must do it before this
}

如果您使用父进程在管道上执行最后一个命令(wc),则根本不需要使用waitpid。但是,如果您想要一个父进程,则可以随意使用它。如果是这样,请在所有子级执行其任务后调用 waitpid

在dup2之前,您不能关闭管道。您发布的错误似乎是由此引起的。

wc: standard input: Bad file descriptor 0 0 0 wc: -: Bad file descriptor

在dup2之后,必须在子进程中关闭管道。
close(pip[0][0]); // it's ok
close(STDOUT_FILENO); // it's ok but not necessary
dup2(pip[0][1],STDOUT_FILENO);
// here you have to close(pip[0][1]) due to you have already duped it in STDOUT_FILENO
execvp(c->args[0],c->args);

如果您要拥有一个父元素,则必须在两个子元素都使用它之后才关闭它。

printf("2 \n");

close(pip[0][1]); 
close(pip[0][0]); // You're closing the file descriptor which wc needs to read.

您没有检查某些函数的所有可能返回状态。

pipe
fork
execvp
dup2

还有其他需要改进的地方

int pip[3][2];  // in your case with `int pip[2]` would be enough
pipe(pip[0]);
pipe(pip[1]);  // in your case you have to create just one pipe

实际上我得到了答案。 我在中间删除了两个关闭语句,并且当我为第二个pid使用了不同的变量时,它起作用了。 因此,问题出在第二个waitpid上,它正在等待错误的pid值。 - Kai

1
我采取了懒惰的方式,写了自己的代码而不是修复其他代码。把它看作是“C语言中的另一个管道拟合示例”,但它可能有助于指出OP代码的问题。
/*
 * hard-wired example program exploring how to implement
 *
 *     system("ls | wc");
 *
 * using calls to pipe(2), fork(2), execvp(2) and wait(2)
 */

#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

static void
do_close(int fd)
{
    if (close(fd) == -1) {
        perror("close");
        exit(1);
    }
}

static void
do_execvp(char *const cmd[])
{
    execvp(cmd[0], cmd);

    /*
     * if execvp returns in this text, an error occured.
     */

    perror("execvp");

    exit(1);
}

static void
dup_and_exec(int fd, int *pp, char *const cmd[])
{
    if (dup2(pp[fd], fd) == -1) {
        perror("dup2");
        exit(1);
    }

    do_close(pp[0]);
    do_close(pp[1]);

    do_execvp(cmd);
}

int
main(void)
{
    char *const ls_cmd[] = { "ls", 0 };
    char *const wc_cmd[] = { "wc", 0 };

    int fds[2];

    int w_stat;
    pid_t ls_pid, wc_pid, w_pid;

    /* create a single pipe to connect our writer and reader processes */

    if (pipe(fds) == -1) {
        perror("pipe");
        exit(1);
    }

    /* create the writer process: ls */

    ls_pid = fork();

    if (ls_pid == -1) {
        perror("fork");
        exit(1);
    }

    if (ls_pid == 0) {
        /* this is the child - do the "ls" command */

        dup_and_exec(1, fds, ls_cmd);   /* no return from here */
    }

    /* create the reader process: wc */

    wc_pid = fork();

    if (wc_pid == -1) {
        perror("fork");
        exit(1);
    }

    if (wc_pid == 0) {
        /* this is the child - do the "wc" command */

        dup_and_exec(0, fds, wc_cmd);   /* no return from here */
    }

    /* parent process */

    /*
     * It's important to close the pipe completely in the parent,
     * so (in particular) there's no process that could be an
     * additional writer to the "write" side of the pipe.
     *
     * We need to arrange things so that our reader process (the "wc"
     * process in this example) will see EOF when the only writer (the
     * "ls" process) closes its output and exits.
     *
     * If this parent process does not close the write side of the pipe,
     * it remains open, since it's shared across fork(2), so the reader
     * (wc) won't ever see EOF and exit, and this parent process won't
     * ever see the wc exit, and everything hangs.
     *
     * The core problems will have started with the parent, which all
     * children know to be true.
     *
     * The next lines also close the "read" side of the pipe, which
     * is a bit cleaner, but won't affect proper operation of this
     * sample program. But closing all un-needed file descriptors is
     * good hygiene: for longer running applications, or for library
     * code that could be called from longer running programs, avoiding
     * any leaks of file descriptors is a good thing.
     */

    do_close(fds[0]);
    do_close(fds[1]);

    while ((w_pid = wait(&w_stat)) > 0) {
        printf("%s process exited", w_pid == ls_pid ? "ls" : "wc");
        if (WIFEXITED(w_stat)) {
            printf(" (status %d)", WEXITSTATUS(w_stat));
        }
        fputs("\n", stdout);
    }

    if (w_pid == -1 && errno != ECHILD) {
        perror("wait");
        exit(1);
    }

    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接