1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- /*
- Implement dup() and dup2() using fcntl() and, where necessary, close(). (You may
- ignore the fact that dup2() and fcntl() return different errno values for some error
- cases.) For dup2(), remember to handle the special case where oldfd equals newfd. In
- this case, you should check whether oldfd is valid, which can be done by, for example,
- checking if fcntl(oldfd, F_GETFL) succeeds. If oldfd is not valid, then the function
- should return –1 with errno set to EBADF .
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <assert.h>
- #include <errno.h>
- int
- dup (int filedes)
- {
- return fcntl (filedes, F_DUPFD, 0);
- }
- int
- dup2 (int oldfd, int newfd)
- {
- if (fcntl (oldfd, F_GETFD) == -1 && errno == EBADF)
- {
- return -1;
- }
- if (oldfd == newfd) return oldfd;
- if (fcntl (newfd, F_GETFD) != -1)
- close (newfd);
- return fcntl (oldfd, F_DUPFD, newfd);
- }
- int
- main (void)
- {
- int fd = dup (STDOUT_FILENO);
- printf ("Testing dup: %d\n", fd);
- write (fd, "test\n", 5);
- close (fd);
- const int newfd = 5;
- fd = dup2 (STDOUT_FILENO, newfd);
- assert (fd == newfd);
- printf ("Testing dup2: %d\n", fd);
- write (fd, "test1\n", 6);
- close (fd);
- fd = open ("test", O_CREAT|O_WRONLY, S_IRWXU);
- dup2 (STDOUT_FILENO, fd);
- printf ("Testing dup2: %d\n", fd);
- write (fd, "test2\n", 6);
- assert (dup2 (10, 2) == -1);
- return EXIT_SUCCESS;
- }
|