Skip to content

Instantly share code, notes, and snippets.

@josephok
Created April 19, 2016 05:06
Show Gist options
  • Save josephok/340828c6af3ae493eddc960ae47171e0 to your computer and use it in GitHub Desktop.
Save josephok/340828c6af3ae493eddc960ae47171e0 to your computer and use it in GitHub Desktop.
implements dup and dup2 using fcntl.
// implements dup and dup2 using fcntl.
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <assert.h>
#include <errno.h>
int mydup(int oldfd);
int mydup2(int oldfd, int newfd);
int mydup(int oldfd) {
int newfd = fcntl(oldfd, F_DUPFD, oldfd + 1);
return newfd;
}
int mydup2(int oldfd, int newfd) {
int fd = fcntl(oldfd, F_GETFL);
if (fd == -1) {
errno = EBADF;
return -1;
}
else {
if (oldfd == newfd) {
return oldfd;
}
else {
close(newfd);
return fcntl(oldfd, F_DUPFD, newfd);
}
}
}
int main(int argc, char const *argv[]) {
int newfd1 = mydup(0);
close(newfd1);
printf("%d\n", newfd1);
int newfd2 = dup(0);
printf("%d\n", newfd2);
close(newfd2);
int fd = open("test.txt", O_RDONLY);
int newfd3 = mydup2(fd, fd);
printf("%d\n", newfd3);
int newfd4 = dup2(fd, fd);
printf("%d\n", newfd4);
close(newfd3);
close(newfd4);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment