首页 > 解决方案 > 实现管道和 execvp 时文件描述符错误

问题描述

我目前正在做一个任务,教我们如何在我的自定义 shell 中实现管道。在我实际在我的 shell 上实现管道并更改我的代码之前,他们希望我们创建两个孩子,并在实现管道时对每个孩子运行一个命令:

在孩子 1 上执行“ls -l” 在孩子 2 上执行“tail -n 2”

目前,我的代码如下所示:

int main (int argc, char * argv[]){
    int debugMode=0;
    int p[2];
    int writeDup;
    int readDup;
    int status;
    if (strcmp(argv[1],"-d")==0)
        debugMode=1;
    if (pipe(p)<0)
        return 0;
    int child1= fork();
    if (child1 == 0)
    {

        if (debugMode == 1)
            fprintf(stderr, "Child 1 is redirecting stdout to write end of pipe.\n");

        fclose(stdout);
        writeDup = dup(p[1]);
        close(writeDup);
        char *args[] = {"ls","-l",NULL};
            
        if (execvp(args[0],args)<0){
            if (debugMode ==1)
                perror("ls -l failed ");
            return 0;
        }
    }
    else
    {
        if (debugMode == 1)
            fprintf(stderr, "Parent process is waiting to close write end of pipe.\n");

        while ((child1=waitpid(-1,&status,0))!=-1);

        close(p[1]);

    }
    int child2 = fork();
    if (child2 == 0)
    {
        fclose(stdin);
        readDup = dup(p[0]);
        close(readDup);

        char *args[] = {"tail","-n","2",NULL};

        if (execvp(args[0],args)<0){
            if (debugMode ==1)
                perror("tail -n 2 failed ");
            return 0;
        }
    }
    else{
        if (debugMode == 1)
            fprintf(stderr, "Parent process is closing read end of pipe.\n");

        while ((child2=waitpid(-1,&status,0))!=-1);
        close(p[0]);
    }
    if (debugMode == 1 && child1 != 0  && child2 !=0)
            fprintf(stderr, "Waiting for child processes to terminate.\n");

    while ((child1=waitpid(-1,&status,0))!=-1 && (child2=waitpid(-1,&status,0))!=-1 );

    return 0;
    
    
}

但是,在执行时,我收到几个错误:

ls: write error : bad file descriptor
tail: cannot fstat 'standard input': Bad file descriptor
tail: -: bad file descriptor

他们要求我们关闭标准输入和输出,因此我假设程序应该默认读取/写入管道。我正在继续尝试找到解决方案,我将不胜感激任何帮助或指导!

标签: cshellpipefork

解决方案


推荐阅读