c - 使用管道进行 fork 过程时程序崩溃

标签 c fork execv broken-pipe write-error

我正在为类(class)作业编写一个基本的 shell,它将在给定的路径列表中查找命令,并执行该命令。它还用于处理管道。 但是,当我 fork 一个子进程时,我在 gdb 中收到“写入错误:损坏的管道”消息,并且程序突然终止。

我似乎无法理解为什么会发生这种情况,因为我一直对打开和关闭正确的管道保持谨慎,并且进程 fork 似乎可以按预期工作。有更多 C 和 UNIX 编程经验的人可以帮我诊断问题吗?我的 fork 实现/管道实现在逻辑上是否有错误?

//commands is of the format {"ls -al", "more", NULL}
//it represents commands connected by pipes, ex. ls -al | more
char **commands = parseArgv(consoleinput, SPECIAL_CHARS[4]);

int numcommands = 0;

while( commands[numcommands]!=NULL )
{
    numcommands++;
}

const int  numpipes = 2*(numcommands-1);

int pipefds[numpipes];

int i=0;
for(i=0; i<numpipes;i=i+2)
{
    pipe(pipefds+i);
}

int pipe_w = 1;
int pipe_r = pipe_w - 3;
int curcommand = 0;

while(curcommand < numcommands)
{
    if(pipe_w < numpipes)
    {
        //open write end
        dup2(pipefds[pipe_w], 1);
    }

    if(pipe_r > 0)
    {
        //open read end
        dup2(pipefds[pipe_r], 0);
    }

    for(i=0;i<numpipes;i++) //close off all pipes
    {
        close(pipefds[i]);
    }

    //Parse current command and Arguments into format needed by execv

    char **argv = parseArgv(commands[curcommand], SPECIAL_CHARS[0]);

    //findpath() replaces argv[0], i.e. command name by its full path ex. ls by /bin/ls
    if(findPath(argv) == 0)
    {
        int child_pid = fork();

        //Program crashes after this point
        //Reason: /bin/ls: write error, broken pipe

        if(child_pid < 0)
        {
            perror("fork error:");
        }
        else if(child_pid == 0)     //fork success
        {
            if(execv(argv[0], argv) == -1)
            {
                perror("Bad command or filename:");
            }

        }
        else
        {
            int child_status;
            child_pid = waitpid(child_pid, &child_status, 0);
            if(child_pid < 0)
            {
                perror("waitpid error:");
            }
        }
    }
    else
    {
        printf("Bad command or filename");
    }
    free(argv);

    curcommand++;
    pipe_w = pipe_w + 2;
    pipe_r = pipe_r + 2;
}

//int i=0;
for(i=0;i<numpipes;i++) //close off all pipes
{
    close(pipefds[i]);
}

free(commands);

最佳答案

在 fork() 调用之后(即在子进程中)复制文件描述符是正确的方法。 此外,waitpid() 调用使一个子进程等待另一个子进程,并且 shell 挂起。 wait() 调用应移至循环之后,即父级应等待所有子级。

关于c - 使用管道进行 fork 过程时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14800293/

相关文章:

c++ - Fork 程序在一段时间后给出 <defunct> 进程

C fork处理全局变量

c - Execv 的参数从第二个元素开始

Java 程序在 JNI 方法调用后终止

c - 内核模块编译中缺少头文件

c - 访问结构的成员或多维数组的每个维的声明边界外

c++ - 异步过程调用

mercurial - 更好地分支或创建Mercurial存储库?

c - execv 如何从管道获取输出?

c - 如何将结构作为参数传递