簡體   English   中英

在C中實現管道時出錯文件描述符錯誤

[英]Bad file descriptor error when implementing piping in C

我正在嘗試實現一個類似於程序的示例shell,它執行命令ls | 廁所

使用管道來實現命令。 當我執行命令時,我收到以下錯誤。

wc:標准輸入:錯誤的文件描述符0 0 0 wc: - :錯誤的文件描述符

請查看代碼並提供輸入注意:1)parse是一個庫,它接受輸入的輸入並將每個命令作為帶有args和necesary數據的鏈表返回。 Parse工作正常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]);
    }

}

一個主要問題是:

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

...

dup2(pip[0][0],STDIN_FILENO);
close(pip[0][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

我采取了懶惰的方式,寫了我自己而不是修復其他代碼。 將其視為“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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM