redirect stdin when using execl

Guy Harris guy at auspex.auspex.com
Tue Jun 13 04:20:37 AEST 1989


(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.



More information about the Comp.unix.wizards mailing list