Write a function of the same dup2 function, cannot call the FCNTL function, and must have error handling __ function

Source: Internet
Author: User

Use the original DUP function of the system when implemented

MYDUP2.C//2015/08/17 Lucifer Zhang version1.0//write my own dup2 function//use DUP () function when inplemen tation #include <unistd.h>//include DUP () #include <stdio.h> #include <stdlib.h> #define OPEN_MAX 25 

6/* When the descriptor is negative or greater than Open_max, 'll make a errro * */int my_dup2 (int fd, int newfd);
    
    int main (int argc, char *argv[]) {int NEWFD, RETURN_FD;
        if (argc!= 2) {printf ("usage:a.out test.txt\n");
    Exit (0);
    printf ("Please input the descriptor than your want to set:");

    scanf ("%d", &AMP;NEWFD);
    Open a file int fd = open (Argv[1], 0);
    if (fd = = 1) {perror (argv[1]);//Print error MSG exit (0);
    printf ("Old descriptor is:%d\n", FD);
    RETURN_FD = My_dup2 (fd, NEWFD);
    printf ("New descriptor is:%d\n");
    Close (FD);

    Close (RETURN_FD);
Exit (0);
    int my_dup2 (int fd, int newfd) {int count = 0; int FDARRY[NEWFD]; 
        Record opened descriptor if (NEWFD < 0 | | | NEWFD > Open_max) {printf ("The New descriptor error!\n");
    Exit (0); }//DUP () return the lowest-numbered available file descriptor if ((Fdarry[count] = DUP (FD)) = = 1) {PR
        Intf ("DUP () function error!\n");
    Exit (0);
    else {//test old file descriptor if can is used close (Fdarry[count]);
    }//If FD equals NEWFD, then Dup2 returns NEWFD without it if (fd = = closing) {return FD; Close (NEWFD); Close//The main implementation for (count = 0; count <= newfd ++count) {if ((fdarry[count) = du
            P (FD) = = = 1) {printf ("dup () Funciont error!\n");
        Exit (0);
            else {printf ("The descriptor is:%d\n", Fdarry[count]);
            if (fdarry[count] = = NEWFD) {break; for (count = 0; count <= newfd; ++count) {if (Fdarry[coUNT] = = NEWFD) {return fdarry[count];
        else {close (Fdarry[count]);
 }
    }
}

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.