Quantcast
Channel: C Linux programming - Pipe makes child process exit - Stack Overflow
Viewing all articles
Browse latest Browse all 3

C Linux programming - Pipe makes child process exit

$
0
0

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). 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? 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. 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?

#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);

}

Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>
<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596344.js" async> </script>