Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!wuarchive!usc!snorkelwacker!bloom-beacon!eru!luth!sunic!mcsun!hp4nl!star.cs.vu.nl!maart From: maart@cs.vu.nl (Maarten Litmaath) Newsgroups: comp.lang.c Subject: Re: Using Macros Message-ID: <7263@star.cs.vu.nl> Date: 9 Aug 90 11:33:18 GMT References: <362.26be9dcc@astro.pc.ab.com> <21057@grebyn.com> <642@travis.csd.harris.com> Sender: news@cs.vu.nl Reply-To: maart@cs.vu.nl (Maarten Litmaath) Organization: VU Dept. of Computer Science, Amsterdam, The Netherlands Lines: 56 In article <642@travis.csd.harris.com>, brad@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 #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)