歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> APUE習題[實現dup2函數功能,不使用fcntl]

APUE習題[實現dup2函數功能,不使用fcntl]

日期:2017/3/3 16:00:33   编辑:關於Linux

學習,記錄。

int dup2(int oldhandle, int newhandle);

函數功能:

復制文件句柄,newhandle指定的dup2和dup的區別就是可以用newfd參數指定新描述符的數值,如果newfd已經打開,則先將其關閉。如果newfd等於oldfd,則dup2返回newfd, 而不關閉它。dup2函數返回的新文件描述符同樣與參數oldfd共享同一文件表項。

關鍵部分實現思路:

先close關閉需要復制到的文件描述符newdup。

連續dup,每dup一次產生的新的fd記錄下來。

當新產生的fd等於需要產生的fd的時候,跳出循環,並把前面產生的fd全都close掉,返回該描述符。

注釋挺詳細,看注釋吧

執行結果:

//Code by Pnig0s1992 
//Date:2012,3,28 
#include <unistd.h> 
#include <fcntl.h> 
#include <string.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
     
     
int my_dup(int olddup,int newdup); 
     
int main(int argc,char ** argv) 
{ 
    int newdup = 3; 
    const char * filename = "newfile.txt"; 
	// 本文URL地址:http://www.bianceng.cn/OS/Linux/201410/45509.htm
    int fd = open(filename,O_RDWR); 
    int newfd = my_dup(fd,newdup); 
    if(write(newfd,"Test new fd.",strlen("Test new fd.")) < 0) 
    { 
        printf("Use new fd write file failed."); 
        exit(2); 
    }else
    { 
        printf("Write successfully."); 
    } 
    exit(0); 
} 
     
int my_dup(int olddup,int newdup) 
{ 
    int tempdup; 
    int icount = 0; 
    int filedesarr[newdup]; 
    if((tempdup = dup(olddup)) == -1) //判斷原文件描述服是否有效 
    { 
        printf("the file desp is invalid."); 
        exit(1); 
    }else
    { 
        close(tempdup); 
    } 
     
    if(newdup == olddup) //若新舊文件描述符相等則直接返回 
    { 
        return olddup; 
    } 
    close(newdup);//關閉要復制的文件描述符 
    for(icount = 0;icount<newdup+1;icount++) //循環復制文件描述符 
    { 
        filedesarr[icount] = 0; 
        tempdup = dup(newdup); 
        if(tempdup < 0) 
        { 
            return -1; 
        }else
        { 
            if(tempdup == newdup) 
            { //若復制後的文件描述符於指定的相等則跳出 
                break; 
            }else{ 
                filedesarr[icount] = 1; //否則將對應下標的數組元素置為1 
            } 
        } 
    } 
    for(icount = 0;icount<newdup+1;icount++) //關閉之前打開的非指定描述符 
    { 
        if(filedesarr[icount] == 1) 
        { 
            close(icount); 
        } 
    } 
    return tempdup; 
}

本文出自 “About:Blank H4cking” 博客,請務必保留此出處http://pnig0s1992.blog.51cto.com/393390/819830

Copyright © Linux教程網 All Rights Reserved