dup (C System Call)
dup is a system call similar to dup2 in that it creates an alias for the provided file descriptor. dup always uses the smallest available file descriptor. Thus, if we called dup first thing in our program, then you could write to standard output by using file descriptor 3 (dup uses 3 because 0, 1, and 2 are already taken by default). You can determine the value of the new file descriptor by saving the return value from dup
Required Include Files
#include <unistd.h>
Function Definition
int dup(int fildes);
| Field | Description |
|---|---|
| int fildes | The file descriptor that you are attempting to create an alias for. |
| return value | dup returns the value of the new file descriptor that it has created (which will always be the smallest available file descriptor). A negative return value means that an error occured. |
Code Snippet
Using dup(), we can create an alias for standard output, as follows:
#include <unistd.h> /*Included for dup(2) and write(2)*/ #include <stdlib.h> /*Included for exit(3)*/ #define MESSAGE "Hey! Who redirected me?\r\n\0" int main() { int newfd = dup(STDOUT_FILENO); /*Call dup for an aliased fd*/ char buff[] = MESSAGE; if (newfd < 0) { /*Negative file descriptors are errors*/ exit(EXIT_FAILURE); } else if (write(newfd, buff, sizeof(buff)) < 0) { /*See: man 2 write*/ exit(EXIT_FAILURE); } return EXIT_SUCCESS; }
You can also use dup() to redirect standard output by taking advantage of the fact that it always uses the smallest available file descriptor:
#include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #define OUTPATH "output" #define MESSAGE "Behold, Standard Out is now a file!" int main() { /*First, we open a file for writing only"*/ int outputfd = -1; outputfd = open(OUTPATH, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU | S_IRGRP | S_IROTH); /*If we have an error, we exit * N.B. file descriptors less than one are invalid*/ if (outputfd < 0) { perror("open(2) file: " OUTPATH); exit(EXIT_FAILURE); } /*Next, we close Standard Out The lowest file descriptor will now be STDOUT_FILENO*/ if (close(STDOUT_FILENO) < 0) { perror("close(2) file: STDOUT_FILENO"); close(outputfd); exit(EXIT_FAILURE); } /*Afterwards, we duplicate outputfd onto STDOUT_FILENO, exiting if the descriptor isn't equal to STDOUT_FILENO*/ if (dup(outputfd) != STDOUT_FILENO) { perror("dup(2)"); close(outputfd); /*N.B. Remember to close your files!*/ exit(EXIT_FAILURE); } close(outputfd); /*If everything succeeds, we may close the original file*/ puts(MESSAGE); /*and then write our message*/ return EXIT_SUCCESS; }
page revision: 13, last edited: 28 May 2012 00:26





