www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/07/08/12:48:29

From: terra AT diku DOT dk (Morten Welinder)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: interesting redir behavior
Date: 8 Jul 1997 15:10:57 GMT
Organization: Department of Computer Science, U of Copenhagen
Lines: 49
Sender: terra AT tyr DOT diku DOT dk
Message-ID: <5ptla1$fng@vidar.diku.dk>
References: <97Jul8.133945gmt+0100 DOT 16649 AT internet01 DOT amc DOT de>
NNTP-Posting-Host: tyr.diku.dk
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019