An existing file descriptor is
duplicated by either of the following functions:
#include <unistd.h>
int dup(int fd);
int dup2(int fd, int fd2);
Both return: new file descriptor
if OK, −1 on error
The new file descriptor returned
by dup is guaranteed to be the lowest-numbered
available file descriptor. With
dup2, we specify the value of the new descriptor with the
fd2 argument. If fd2
is already open, it is first closed. If fd equals fd2, then
dup2 returns
fd2 without closing
it. Otherwise, the FD_CLOEXEC file descriptor flag is cleared for fd2,
so that fd2 is left open if the process calls
exec.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
char arr[] = "my name is
mydup\n";
int main()
{
int fd1, fd2;
char pidstr[128] = "\0";
fd1 = open ("~/test/file_for_dup", O_CREAT|O_RDWR);
if (fd1 < 0) {
perror ("open");
exit(-1);
}
sprintf (pidstr, "/proc/self/fd/%d", fd1);
printf ("pidstr: %d %s\n", fd1, pidstr);
write (fd1, arr, sizeof(arr));
fd2 = open (pidstr, O_RDWR);
if (fd2 < 0) {
perror ("open");
exit(-1);
}
lseek (fd2, sizeof (arr), SEEK_SET);
write (fd2, arr, sizeof(arr));
close (fd2);
close (fd1);
}