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.
/*
* Linux Program to Duplicate a File Descriptor with fcntl().
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int fd, nfd;
if (argc < 2) {
printf("Usage : %s pathname\n", argv[0]);
exit(1);
}
/* opening the file in write-only mode */
if ((fd = open(argv[1], O_WRONLY)) < 0) {
perror("Problem in opening the file");
exit(1);
}
/* duplicating fd with nfd */
if ((nfd = fcntl(fd, F_DUPFD, 0)) == -1) {
perror("Problem in duplicating fd");
exit(1);
}
printf("Fd %d duplicated with %d\n", fd, nfd);
close(fd);
close(nfd);
}
$ 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.
Related Posts:
- Practice Programming MCQs
- Apply for Linux Internship
- Buy Linux Books
- Buy Information Technology Books
- Apply for Programming Internship