Linux Program to Duplicate a File Descriptor with fcntl()

This Linux Program illustrates Duplicating a File Descriptor with fcntl().

Here is the source code of Linux Program to Duplicate a File Descriptor with fcntl(). The Linux Program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2. * Linux Program to Duplicate a File Descriptor with fcntl().
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10. #include <fcntl.h>
  11.  
  12. int main(int argc, char **argv)
  13. {
  14.     int fd, nfd;
  15.  
  16.     if (argc < 2) {
  17.         printf("Usage : %s pathname\n", argv[0]);
  18.         exit(1);
  19.     }
  20.  
  21.     /* opening the file in write-only mode */
  22.     if ((fd = open(argv[1], O_WRONLY)) < 0) {
  23.         perror("Problem in opening the file");
  24.         exit(1);
  25.     }
  26.  
  27.     /* duplicating fd with nfd */
  28.     if ((nfd = fcntl(fd, F_DUPFD, 0)) == -1) {
  29.         perror("Problem in duplicating fd");
  30.         exit(1);
  31.     }
  32.     printf("Fd %d duplicated with %d\n", fd, nfd);
  33.  
  34.     close(fd);
  35.     close(nfd);
  36. }

 
$ gcc dup_fd.c
$ a.out my_file
 
Fd 3 duplicated with 4

Sanfoundry Global Education & Learning Series – 1000 Linux Programs.

advertisement
advertisement
If you wish to look at all Linux Programming examples, go to Linux Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.