This is the mail archive of the glibc-linux@ricardo.ecn.wfu.edu mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: pipe() in glibc2.0.7


On Sun, 10 Oct 1999, Bernd Rinn wrote:

> call should not block, if the file-descriptor is a pipe, that has been
> closed on the writing side, but should instead return with EOF
> (i.e. 'read()' should return 0).

Note that the read() function is a wrapper for the read system call.
The semantics are determined by the underlying kernel.

> int 
> main(void)
> {
>   pid_t pid, p;
>   int status;
>   int mypipe[2];
> 
> if (pipe(mypipe))
>   {
>     fprintf(stderr, "Pipe failed.\n");
>     return EXIT_FAILURE;
>   }
> 
> pid = fork();
> if (pid == (pid_t)0)
>   {

+     close(mypipe[0]);	/* oops, forgot! */

>     write_to_pipe(mypipe[1]);
>     return EXIT_SUCCESS;
>   }

Note that exiting from the child should probably done by _exit().

>   {
>     fprintf(stderr, "child PID %d\n", pid);

+     close(mypipe[1]);	/* oops, forgot! */

      
>     read_from_pipe(mypipe[0]);
>     p = waitpid(pid, &status, 0);

The closes are important. If the parent does not close one half of the pipe,
then that pipe remains valid. 

When you fork a child process, it receives file descriptor duplicates. Both the
parent and child must close a file descriptor before the object it refers to
(socket, pipe, file, terminal, whatever) is destroyed.  By not destroying the
unused descriptor in the parent, you have ensured that the pipe will never be
closed and your program will deadlock on shutdown.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]