Mail Archives: djgpp/1997/07/08/12:48:29
Chris Croughton <crough45 AT amc DOT de> writes:
>Under all other versions of MSDOS C I've used (Borland
>and MS, several versions of each) saying:
> int fd = open("...", ...);
> dup2(fd, 1);
>has worked fine...
It ain't that easy, unless you can guarantee that file handles 0-2
were in use before you started the redirection boogie. If your
program is started by command.com you're fine.
The problem is that your open() might give you a handle in the range
you want to use yourself, i.e., 0-2. You must "move" it out of that
range before you start redirecting, or else one of your dup2's might
end up closing the file(!)
Morten
/* ------------------------------------------------------------------------- */
/* Move a file descriptor FD such that it is at least MIN_FD. If the file
descriptor is changed, the old one will be freed. A -1 will be returned
is the operation fails. In that case the old descriptor is still valid. */
static int
move_fd (int fd, int min_fd)
{
int new_fd, tmp_fd;
if (fd == -1 || fd >= min_fd) return fd;
tmp_fd = dup (fd);
if (tmp_fd == -1) return -1;
new_fd = move_fd (tmp_fd, min_fd);
if (new_fd != -1)
close (fd); /* Success -- get rid of original descriptor. */
else
close (tmp_fd); /* Failure -- get rid of temporary descriptor. */
return new_fd;
}
/* ------------------------------------------------------------------------- */
- Raw text -