want workaround for "dup2"

Thomas J. Pusateri pusateri at duke.cs.duke.edu
Mon Mar 18 12:06:15 AEST 1991


In article <1270 at hico2.UUCP> kak at hico2.westmark.com writes:
>Is there an easy way to provide dup2?

I don't have my sysv manuals in front of me, but one can usually use
fcntl (at least the BSD version, which may not help!) 

To perform:
	dup2(old, new)
Try:
	close(new);		/*  guarentees new is not in use */
	fcntl(old, F_DUPFD, new);

If this isn't in unix-pc fcntl, then you still have a few options.
You just have to make sure that new is the next available slot
in the descriptor table. This could be accomplished with a bunch
on open()'s to fill unwanted slots, then a normal dup, and last a bunch
of close()'s which is kind of ugly, or if you are trying to fill a
stdio slot, then just close it before you do a dup. For instance,
to redirect stdin so it comes from a file, it is easiest to do the
following when you have dup2():
	new = open(...
	dup2(new, 0);
	close(new);

But this can be accomplished almost as easily by:

	new = open(...
	close(0);
	dup(new);
	close(new);

It depends on your application.

Tom Pusateri
Duke University

pusateri at nbsr.duke.edu



More information about the Comp.sys.3b1 mailing list