zoukankan      html  css  js  c++  java
  • 写一个dup2功能同样的函数,不能调用 fcntl 函数,而且要有出错处理

    实现的时候用到系统原来的dup函数

    // mydup2.c
    // 2015/08/17    Lucifer Zhang    version1.0
    // write my own dup2 function
    // use dup() function when inplementation
    
    #include <unistd.h> // include dup()
    #include <stdio.h>
    #include <stdlib.h>
    
    #define OPEN_MAX 256
    /*
     * when the descriptor is negative or greater than OPEN_MAX, will 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
    ");
            exit(0);
        }
        printf("Please input the descriptor than you want to set: ");
        scanf("%d", &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
    ", fd);
        return_fd = my_dup2(fd, newfd);
        printf("new descriptor is: %d
    ");
        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!
    ");
            exit(0);
        }
    
        // dup() return the lowest-numbered available file descriptor
        if ((fdarry[count] = dup(fd)) == -1) {
            printf("dup() function error!
    ");
            exit(0);
        } else { // test old file descriptor if can be used
            close(fdarry[count]);
        }
    
        // if fd equals newfd, then dup2 returns newfd without closing it
        if (fd == newfd) {
            return fd;
        }
    
        close(newfd); // close
    
        // the main implementation
        for (count = 0; count <= newfd; ++count) {
            if ((fdarry[count] = dup(fd)) == -1) {
                printf("dup() funciont error!
    ");
                exit(0);
            } else {
                printf("the descriptor is: %d
    ", fdarry[count]);
                if (fdarry[count] == newfd) {
                    break;
                }
            }
        }
    
        for (count = 0; count <= newfd; ++count) {
            if (fdarry[count] == newfd) {
                return fdarry[count];
            } else {
                close(fdarry[count]);
            }
        }
    }
    

  • 相关阅读:
    winform访问https webservice
    rabbitMQ访问失败
    Redis断线测试
    微信消息推送
    线程控制
    Oracle.ManagedDataAccess.dll折腾了我两天
    IPC网络摄像机rtsp视频流web上H5播放方法
    微软补丁下载网站(备忘)
    ABP vnext 种子文件更新
    ABP vnext 使用Swagger账号登录时Chrome浏览器提示【The cookie 'XSRF-TOKEN' has set 'SameSite=None' and must also set 'Secure'.】错误,不能跳转登录
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/7228199.html
Copyright © 2011-2022 走看看