[comp.lang.c] Why can't stdin from a file be read by an overlay?

lvc@tut.UUCP (12/04/87)

I am using Unix System 5 Release 2 on an AT&T 3b5 and have seen
the problem below many times and don't know what to do about it.

Suppose a program reads stdin, prompts the user for some infor-
mation, and then execs (no fork) a process to finish prompting
the user for other information.  There isn't a problem when the
input is from a tty, however, if the input is redirected, say
from a Bourne shell here document, the second process sees an
EOF immediately.

Any ideas on what might be wrong here and how to correct it?
Does the shell use close-on-exec for stdin? Yes it design is
insane but it has to be done this way.  Thanks,

-- 
	Larry Cipriani AT&T Network Systems at
	cbosgd!osu-cis!tut!lvc Ohio State University

chris@mimsy.UUCP (12/05/87)

In article <2775@tut.cis.ohio-state.edu> lvc@tut.cis.ohio-state.edu
(Lawrence V. Cipriani) writes:
>Suppose a program reads stdin ... for some information, and then
>execs (no fork) a process to [read] other information.  There
>isn't a problem when the input is from a tty, however, if the
>input is redirected, say from a Bourne shell here document, the
>second process sees an EOF immediately.

The here document (or other input file) has no more than a `block'
(BUFSIZ) of stuff.  stdio is reading the entire block; then when
the program exec()s, the part of that block that has not been used
simply vanishes, because the seek offset for fd 0 is still at
end-of-file.

Solutions: avoid stdio; use unbuffered input; cheat and seek fd 0
to the right place, the latter with lseek(0, ftell(stdin), 0).
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7690)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris

gwyn@brl-smoke.ARPA (Doug Gwyn ) (12/05/87)

In article <2775@tut.cis.ohio-state.edu> lvc@tut.cis.ohio-state.edu (Lawrence V. Cipriani) writes:
>Suppose a program reads stdin, prompts the user for some infor-
>mation, and then execs (no fork) a process to finish prompting
>the user for other information.  There isn't a problem when the
>input is from a tty, however, if the input is redirected, say
>from a Bourne shell here document, the second process sees an
>EOF immediately.

Probably the input is being fully-buffered, which means that
the original has consumed more input than you intended, which
is lost when the exec() occurs.  The solution would be to use
setbuf() or setvbuf() to use unbuffered or line-buffered
input for stdin.  That should prevent stdio from reading ahead.

lvc@tut.cis.ohio-state.edu (Lawrence V. Cipriani) (12/08/87)

Thanks to everyone that sent me mail.  All I had to do was to add:

	if (!isatty(0))
		setbuf(stdin, (char *)0);

(as several of you suggested) before the program started reading,
and everything worked fine.

-- 
	Larry Cipriani AT&T Network Systems at
	cbosgd!osu-cis!tut!lvc Ohio State University