Tuesday, 23 February 2016

Write your own dup2 function that performs the same service as the dup2 function described in Section 3.12, without calling the fcntl function. Be sure to handle errors correctly.

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);

}

2 comments:

  1. Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. Fabulous post. Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites. I'll be sure to check back again real soon.
    cs代写

    ReplyDelete
  2. Wonderful topics with determinate explanation... Very nice blog with fabulous post .. sure to come back for more

    ReplyDelete