Re: fork and pipe



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

.



Relevant Pages

  • Re: A tricky problem about Process.wait and popen
    ... There is a parent process and a fixed number of child processes. ... using IO.popen and then wait for any child process exits. ... it will read correspondant pipe to get result ... puts "Started" ...
    (comp.lang.ruby)
  • Re: Read console output and store it into buffer ?
    ... Parent process wait for child process end and display resulft of ... What part do you have trouble with? ... In child process returns 0): ... Close read end of pipe using close ...
    (comp.os.linux.development.apps)
  • Re: A tricky problem about Process.wait and popen
    ... There is a parent process and a fixed number of child processes. ... using IO.popen and then wait for any child process exits. ... it will read correspondant pipe to get result ...
    (comp.lang.ruby)
  • Re: How to time out a forked command but still see output?
    ... Again, if the program hangs and there's a timeout, then the handler ... closes the pipe and launchs the program in the ... be aware the child process will ... terminate with a SIGPIPE as soon as it tries to write to the closed ...
    (comp.lang.perl.misc)
  • Re: Pipes on Wince (I have them), and device auto-loading.
    ... appropriate paths for each child process. ... the device nature of the pipe from the user, ... like to somehow have the device auto deactivate when the last ... In PipeLib there is a thread that waits ...
    (microsoft.public.windowsce.embedded)