Re: fork and pipe
- From: "Lew Pitcher" <lpitcher@xxxxxxxxxxxx>
- Date: 1 Feb 2007 05:08:09 -0800
On Feb 1, 4:27 am, "baumann@pan" <baumann....@xxxxxxxxx> wrote:
Hi all,
I don't understand why close one pipefd is needed in code below:
Please review the pipe(7) and pipe(2) documentation.
In summary, the pipe(2) call creates a single, unidirectional pipe,
and returns fds to both the write end and the read end of the pipe.
The reading process doesn't need (and can't use) the write end of the
pipe, and usually closes it. The writing process doesn't need (and
can't use) the read end of the pipe, and usually closes it.
[code snipped]
while child process need to close fd[1], and why parent close fd[0]?
Neither process /needs/ to close their respective unused ends of the
pipe. However, it is good programming practice to close unused files,
and the programmer here does so.
what fork will do when inherit those fds?
OK, you don't understand the implications of pipe(2) and fork(2), so
lets review
Parent process
1) The parent process calls pipe(2) to open two fds. fd[0] is for
input and fd[1] is for output
2) the parent process calls fork(2) to spawn a child process
3) the parent process closes fd[0] because it won't be reading from it
4) the parent process writes a message to fd[1]
Child process
1) the child process inherits all open fds from the parent process,
including the two open fds from the parent's pipe(2) call
2) the child process closes fd[1] because it wont be writing to it
3) the child process reads a message from fd[0]
HTH
--
Lew
.
- Follow-Ups:
- Re: fork and pipe
- From: phil-news-nospam
- Re: fork and pipe
- References:
- fork and pipe
- From: baumann@pan
- fork and pipe
- Prev by Date: Re: fork and pipe
- Next by Date: Re: gethostbyname + timeout
- Previous by thread: Re: fork and pipe
- Next by thread: Re: fork and pipe
- Index(es):
Relevant Pages
|