Frage

In my program , I use fork and execvp to create a child process. Now i want to direct the output of the childprocess to both stdout and to a file in the current directory. So how can this be achieved?

War es hilfreich?

Lösung

You can't have one file descriptor be tied to two things - there is no way to make write(x, "hello world") write to both std out and a file. Instead, you have to have three files - the child's standard out fd, which the parent reads from, the parent's standard out fd and the parent's fd to a file.

Here's what you do:

  • Parent dups fd 0 to some other fd (the parent's std out needs to be moved to something other than 0).
  • Parent calls pipe() to create a pipe, and if necessary dup2()'s it to put it on fd 0.
  • Parent opens the output file that is to be written to.
  • Parent forks the child.
  • The child process inherits the open FDs of the parent, including the pipe on fd 0 and the open file.
  • Child closes the FD for the output file.
  • Child execs the actual program.
  • Child will write to fd 0 (which happens to be the pipe created by the parent) as it normally does.
  • Parent will read from the pipe and will write to the moved FD for its std out and will also write to the FD for the output file.

The loop that reads from the pipe and writes to stdout and the output file has to run until the child closes its end of the pipe, so you may need to create a thread to do this in the background.

FYI, this is how every shell in the world implements pipes ala cat file | grep hello

Andere Tipps

you should read about select() system call that can be used to direct i/p or o/p to multiple file descriptor do 'man select'

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top