Using Macros
Maarten Litmaath
maart at cs.vu.nl
Thu Aug 9 21:33:18 AEST 1990
In article <642 at travis.csd.harris.com>,
brad at SSD.CSD.HARRIS.COM (Brad Appleton) writes:
)...
)As another example, if you didnt have the dup2() system call on your Unix
)system and wanted to write a macro for it, you could use the following:
)
) #define dup2(to,from) ( (close(from) || (to = dup()) < 0) ? -1 : 0 )
)
)If there is some reason why this would not give the same results as dup2()
)(and fail for the same reasons) then let me know. The main problem I foresee
)is that I cant have a file-descriptor numbered lower than `from' available
)before I make the dup2() call.
The main problem is your definition being wrong. Try the following instead:
#define dup2(from, to) (close(to), dup(from))
It still fails if to == from. This probably gets it right:
#include <sys/errno.h>
#define MAXFD 19 /* archaic */
int dup2(from, to)
int from, to;
{
int fds[MAXFD + 1];
register int *fdp = fds, fd;
extern int errno;
if (from < 0 || from > MAXFD || to < 0 || to > MAXFD) {
errno = EBADF;
return -1;
}
if (from == to)
return to;
while ((fd = *fdp++ = dup(from)) < to && fd >= 0)
;
if (fd != to) {
close(to);
(void) dup(from);
if (fd < 0)
--fdp;
}
while (fdp > fds)
close(*--fdp);
return to;
}
--
"UNIX was never designed to keep people from doing stupid things, because
that policy would also keep them from doing clever things." (Doug Gwyn)
More information about the Comp.lang.c
mailing list