Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sun-barr!olivea!mintaka!bloom-picayune.mit.edu!athena.mit.edu!jik From: jik@athena.mit.edu (Jonathan I. Kamens) Newsgroups: comp.unix.questions Subject: Re: Redirecting stdout, and then getting it back Message-ID: <1991Feb14.201944.18088@athena.mit.edu> Date: 14 Feb 91 20:19:44 GMT References: <1991Feb14.035930.20173@berlioz.nsc.com> Sender: news@athena.mit.edu (News system) Organization: Massachusetts Institute of Technology Lines: 40 It sounds to me like your problem is that you are replacing stdout and stderr too early. If you are running programs in a subprocess and you want the stdout and stderr of those programs to go into a file (or into a pipe from which you can read), then you don't want to close stdout and stderr in the parent before you fork() to start the sub-process; you want to do it after you've fork()ed but before you exec() the sub-process. Now, I realize that if you're using system() right now to start the sub-processes, then you don't have control over this, because system() deals with the fork() and exec() stuff. This means that you're going to have to change the way you're doing things. If you want stdout and stderr to go to a file, then you can do that by simply doing a fork(), then doing the freopen() calls in the child the same way you're doing them in the parent right now, then doing the system() as you're doing now. Since the freopen() calls are in a subprocess, the parent keeps its stdout and stderr. If you do this, don't forget to install a SIGCHLD handler to wait for your children (see the article I posted about that yesterday). Alternatively, you can rewrite system() to do the freopen() calls itself, after its fork() but before its exec(). Pipes are a bit more complicated. You would need to create the pipe in the parent, then do the fork(), then replace fileno(stdout) and fileno(stderr) with the write side of the pipes in the child and close the read sides; in the parent, you close the write sides and read from the read sides to get the output of the subprocess. Then, you do the system() in the child. Of course, there is a much simpler answer to all of this -- you could freopen() /dev/tty on top of stdout and stderr after the subprocess finishes. But this is sloppy programming and I wouldn't recommend it (I'm just mentioning it for completeness). -- Jonathan Kamens USnail: MIT Project Athena 11 Ashford Terrace jik@Athena.MIT.EDU Allston, MA 02134 Office: 617-253-8085 Home: 617-782-0710