Xref: utzoo comp.lang.c:19297 comp.unix.wizards:16897 Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!cs.utexas.edu!uunet!auspex!guy From: guy@auspex.auspex.com (Guy Harris) Newsgroups: comp.lang.c,comp.unix.wizards Subject: Re: redirect stdin when using execl Message-ID: <1813@auspex.auspex.com> Date: 12 Jun 89 18:20:37 GMT References: <851@pcsbst.UUCP> <5587@goofy.megatest.UUCP> <2489@mit-caf.MIT.EDU> Reply-To: guy@auspex.auspex.com (Guy Harris) Followup-To: comp.unix.questions Organization: Auspex Systems, Santa Clara Lines: 45 (Followups redirected to "comp.unix.questions", which was the place where the original question should probably have appeared.) >I think a much better way, under BSD, is to use freopen() to attach >stdin to the redirected file. Such redirection is, in fact, precisely >the intended usage of this function call. When using "freopen()" in this case, the implementations on all the UNIX systems with which I'm familiar it will do: 1) an "fclose" of "stdin", which closes the standard input ("standard input" is file descriptor 0, to which "stdin" happens to refer; it's not "stdin" itself) by virtue of doing a "close" on "stdin"s file descriptor (as indicated, FD0, barring some unlikely train of events); 2) an "open" of the new file, which, if file descriptor 0 was recently closed, should yield 0 as the new file descriptor. The net result will, in fact, make FD0 point to the new file. "freopen()" also does some fiddling with standard I/O information for "stdin", which is not necessary here (since the "execl" will, on most if not all UNIX/POSIX implementations, cause the process's data space to be discarded, and thus discard all the standard I/O information for that process). So "freopen()" is basically a convenient wrapper for the underlying operations the program should do anyway. >Is freopen() a Berklism, No, it's been in UNIX for quite a while - V7 at least. >The original example, passing the string "<" and the redirected file, >was so innocently misguided I really got a laugh out of it. >execl()'ing "/bin/sh" to parse the command, or using system(), on the >other hand, were somewhat less amusing. I'd certainly say they were less amusing, since they actually form a fairly convenient wrapper for these kinds of operations, and would seriously consider using them for this sort of thing. If the guy wanted to redirect the input of "mail" to a pipe from some other program, for example, using "system" (or an "execl()" of "/bin/sh" with the "-c" flag, which is what "system()" does after it does the "fork()") is a lot more convenient than constructing the pipeline yourself.