dup2 (C System Call)

dup2 is a system call similar to dup in that it duplicates one file descriptor, making them aliases, and then deleting the old file descriptor. This becomes very useful when attempting to redirect output, as it automatically takes care of closing the new file descriptor, performing the redirection in one elegant command. For example, if you wanted to redirect standard output to a file, then you would simply call dup2, providing the open file descriptor for the file as the first command and 1 (standard output) as the second command.

Required Include Files

#include <unistd.h>

Function Definition

int dup2(int fildes, int fildes2);
Field Description
int fildes The source file descriptor. This remains open after the call to dup2.
int fildes2 The destination file descriptor. This file descriptor will point to the same file as filedes after this call returns.
return value dup2 returns the value of the second parameter (fildes2) upon success. A negative return value means that an error occured.

Code Snippet

Using dup2(), we can redirect standard output to a file, as follows:

#include <iostream>
#include <unistd.h>
#include <fcntl.h>
using namespace std;
int main()
    //First, we're going to open a file
    int file = open("myfile.txt", O_APPEND | O_WRONLY);
    if(file < 0)    return 1;
    //Now we redirect standard output to the file using dup2
    if(dup2(file,1) < 0)    {
        return 1; // this can return 0 normally
    //Now standard out has been redirected, we can write to
    // the file
    cout << "This will print in myfile.txt" << endl; 
    //At the end the file has to be closed:
    return 0;
}//end of function main
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License