Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!samsung!spool2.mu.edu!uunet!mcsun!hp4nl!star.cs.vu.nl!maart From: maart@cs.vu.nl (Maarten Litmaath) Newsgroups: comp.unix.questions Subject: Re: Reopening stdin Message-ID: <8685@star.cs.vu.nl> Date: 8 Jan 91 01:47:11 GMT References: <5200@trantor.harris-atd.com> Sender: news@cs.vu.nl Reply-To: maart@cs.vu.nl (Maarten Litmaath) Organization: VU Dept. of Computer Science, Amsterdam, The Netherlands Lines: 40 In article <5200@trantor.harris-atd.com>, chuck@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@berlin.mt.cs.cmu.edu: "I heard that an Awk was spotted in Sherwood forest." rmk@frog.UUCP (Rick Kelly): "It was seen running in the background."