Reopening stdin
Maarten Litmaath
maart at cs.vu.nl
Tue Jan 8 12:47:11 AEST 1991
In article <5200 at trantor.harris-atd.com>,
chuck at trantor.harris-atd.com (Chuck Musciano) writes:
)
) Environment: Sun-3/60 running SunOS 4.1
)
) I have a program which at one point forks itself. The child, in turn,
)calls system() to run a command. In the child, I would like to reopen stdin
)to point to a particular file. To do this, I call open() and dup2() before
)calling system().
)
) Here is the strange behavior. If the parent has at some point closed
)its stdin, the command that the child invokes with system() terminates
)with "stdin: bad file number". If the parent does not close its stdin, all
)works fine. The close of stdin occurs before the child is forked.
Does the following program fail too?
main()
{
int fd, i;
close(0);
fd = open("/etc/passwd", 0);
dup2(fd, 0);
i = system("cat");
exit(i & 0377 ? i | 0200 : i >> 8);
}
If so, it looks like a resurrection of the old dup2() bug: as stdin has
been closed, the open() will return file descriptor 0, so the next line
results in
dup2(0, 0)
Old implementations of dup2(from, to) did NOT check for the case
from == to, but blindly closed `to' and duplicated `from' to `to',
so in our case stdin would get closed again... :-(
Have you checked the return value of dup2()?
--
nlp at berlin.mt.cs.cmu.edu: "I heard that an Awk was spotted in Sherwood forest."
rmk at frog.UUCP (Rick Kelly): "It was seen running in the background."
More information about the Comp.unix.questions
mailing list