简体   繁体   English

C Linux编程-管道使子进程退出

[英]C Linux programming - Pipe makes child process exit

I am having a hard time understanding the behavior of the following code. 我很难理解以下代码的行为。 Closing the file descriptor p[0] makes the program exit (since otherwise the parent process just waits on the child processes in all eternity). 关闭文件描述符p [0]使程序退出(因为否则父进程将在所有永恒的时间内都等待子进程)。 It doesn't make sense to me because the child processes are running an infinite while loop, why would they just exit because the read end of the pipe is closed? 这对我来说没有意义,因为子进程正在运行一个无限的while循环,为什么它们会因为管道的读取端已关闭而退出? Sure, you won't be able to write to the pipe but the while loop is not dependent on whether the read end of the parent process is open or not. 当然,您将无法写入管道,但是while循环并不取决于父进程的读取端是否打开。 I tried removing the exit() functions in the child processes and the program exits anyways, so why is the child process killing itself as soon as it notices that the read end is closed? 我尝试删除子进程中的exit()函数,并且该程序始终退出,那么为什么子进程一旦发现读取端已关闭,为什么会自行终止?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

main()
{
    int run=10, fd[2]; pipe(fd); srand(time(0)); char ch, x='x', o='o'; 

    if(!fork())
    {
        close(fd[0]);

        while(run)
        {
            sleep(1+rand()%6); write(fd[1],&x,1);
        }

        exit(0); //This exit doesn't happen
    }

    if(!fork())
    {
        close(fd[0]);

        while(run)
        {
            sleep(1+rand()%3); write(fd[1],&o,1);
        }

        exit(0); //This exit doesn't happen
    }

    close(fd[1]);
    while(run--)
    {
        read(fd[0],&ch,1);
        printf("%d %c\n",run,ch);
        sleep(1);
    }

    close(fd[0]); //closing this file descriptor results in that the program can exit
    wait(0);
    wait(0);
    exit(0);

}

That's standard behavior. 这是标准行为。 You close the read-end of the pipe, so there is nowhere to write. 您关闭管道的读取端,因此无处可写。 That results in a SIGPIPE signal being sent to the writing process. 这导致SIGPIPE信号被发送到写入过程。

The default behavior of SIGPIPE is to terminate the process receiving the signal. SIGPIPE的默认行为是终止接收信号的过程。

If you want your process to survive the signal, you have to catch or ignore it. 如果您希望过程在信号中幸存下来,则必须捕获或忽略它。 Then you must check the result of write as it will return with an error when the pipes read-end is closed. 然后,您必须检查write结果,因为在关闭管道读取端时它将返回错误。

Your problem is not with pipe. 您的问题不在于管道。 Two header files missing in your codes and for which it is crashing when calling wait() function. 您的代码中缺少两个头文件,并且在调用wait()函数时它们会崩溃。 Add below two header files in your program and it will fix your problem. 在程序中添加下面的两个头文件,它将解决您的问题。 Also your declaration of main function is old c type declaration make it like void main() . 同样,您对main函数的声明是旧的c类型声明,使其像void main()

<sys/types.h>
<sys/wait.h>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM