Linux system Programming--Copying of file descriptors: DUP () and dup2 ()

Source: Internet
Author: User

DUP () and dup2 () are two very useful system calls that are used to copy the descriptor of a file so that the new file descriptor also identifies the file identified by the old file descriptor.


This process is similar to the real life of the key, the key equivalent to the file descriptor, the lock is equivalent to a file, a key to open a lock, equivalent to a file descriptor corresponding to a file, now, we go to the key, with the old key copied a new key, In this case, the old key and the new key will open the lock. In contrast to the DUP (), dup2 () , a new file descriptor is copied from the original file descriptor, so that both the original file descriptor and the new file descriptor point to the same file, and we manipulate any one of the two file descriptors to manipulate the corresponding file.


Required header file :

#include <unistd.h>


int dup (int oldfd);

features :

A new file descriptor is copied through OLDFD, and the new file descriptor is the smallest available file descriptor in the calling process file descriptor table, and the final OLDFD and the new file descriptor point to the same file.

Parameters :

OLDFD: The file descriptor that needs to be copied OLDFD

return value :

Success: New File descriptor

Failed:-1


The following example opens a file, copies the file descriptor, and writes the file separately by 2 descriptors:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include < sys/stat.h> #include <fcntl.h> #include <string.h>int main (int argc, char *argv[]) {int Fd1;int fd2;// Open File Fd1 = open ("1.txt", o_creat| O_wronly, 0666); if (Fd1 < 0) {perror ("open"); exit (-1);} printf ("Fd1 ==============%d\n", fd1);//FD1 copied out fd2, final fd1, fd2 all pointing to 1.txtfd2 = DUP (FD1);p rintf ("Fd2 ==============% D\n ", fd2); char *buf1 =" This was a test for fd1\n ";//operation Fd1 file descriptor write (FD1, BUF1, strlen (BUF1)); char *buf2 =" This is a T EST for fd2\n ";//operation Fd2 file descriptor write (FD2, Buf2, strlen (BUF2));//Close the file descriptor, all two have close (FD1); close (FD2); return 0;}

The results of the operation are as follows:



The result of the above operation shows that thenew file descriptor copied after DUP () is the smallest available file descriptor automatically assigned by the system.


Next, let's write an example of what would have been shown to the screen through printf (), not on the screen, but in a file:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include < Sys/stat.h> #include <fcntl.h>int main (int argc, char *argv[]) {int fd1;int fd2;//opening file FD1 = open ("1.txt", o_creat | O_wronly, 0666); if (Fd1 < 0) {perror ("open"); exit (-1);} printf ("Fd1 ==============%d\n", fd1);//1 originally pointing to the standard output device (e.g., display)//1 file descriptor is closed, that is, 1 no longer points to the standard output device//So, 1 file descriptor is idle, it becomes the smallest available text The component descriptor close (1),//through FD1 copy out Fd2, finally fd1, fd2 all point to "1.txt"//The system will assign FD2 a minimum available file descriptor 1, that is fd2 = 1fd2 = DUP (FD1);//The contents of this sentence will not be played Printed to the screen, and will write to the file "1.txt" in//printf () is the standard library function, will eventually call the system call function write ()//equivalent to this, write (1,), to 1 file descriptor write content,//default case, 1 The file descriptor points to the standard output device (e.g., display)//So the contents of printf () are displayed first on the screen//But now the 1 file descriptor points to the file "1.txt"//So the contents of printf () are written to the file "1.txt" printf ("Fd2 ===== =========%d\n ", FD2); close (FD1); close (FD2); return 0;}

The results of the operation are as follows:



Next, we continue to learn the use of dup2 (), which is exactly the same as the DUP (), but the new file descriptor Dup2 () can specify any valid number.


int dup2 (int oldfd, int newfd)

features :

A new file descriptor NEWFD is copied through OLDFD, and if successful, the NEWFD and function return values are the same return value, and the final OLDFD and the new file descriptor NEWFD all point to the same file.

Parameters :

OLDFD: File descriptor that needs to be copied

NEWFD: The new file descriptor, which can be used to specify a legal number (0-1023), if the specified number of children is already occupied (and associated with a file), this function will automatically turn off close () disconnect this number and a file association, Use this legal number again.

return value :

Success: Return to NEWFD

Failure: Return-1


Next, we will replace the above example with dup2 () to achieve:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include < Sys/stat.h> #include <fcntl.h>int main (int argc, char *argv[]) {int fd1;int fd2;//opening file FD1 = open ("1.txt", o_creat | O_wronly, 0666); if (Fd1 < 0) {perror ("open"); exit (-1);} printf ("Fd1 ==============%d\n", fd1);//FD1 copied out fd2, finally fd1, fd2 all point to "1.txt"//Specify FD2 value is 1, 1 originally point to standard output device, first close (), then re- System fd2 = Dup2 (fd1, 1);//The contents of the following sentence will not be printed to the screen, but write to the file "1.txt" in//printf () is the standard library function, and eventually call the system call function write ()//equivalent, write (1,), to 1 File descriptor write content,//By default, 1 file descriptors point to standard output devices (e.g., display)//So the contents of printf () first appear on the screen//But now the 1 file descriptor points to the file "1.txt"//So the contents of printf () are written to the file "1.t XT "printf (" Fd2 ==============%d\n ", FD2); close (FD1); close (FD2); return 0;}

The results of the operation are as follows:



For this tutorial sample code download please click here.

Linux system Programming--Copying of file descriptors: DUP () and dup2 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.