深入理解计算机系统

dup和dup2函数实现

2020-01-21  本文已影响0人  MachinePlay

dup

unix-liked操作系统中,复制文件描述符的函数dup和dup2

int dup(int i)
int  dup(int i , int cmd, ***)

由于题目要求不能使用fcntl函数,所以考虑使用dup函数来实现,思路如下:

#include <iostream>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stack>
int my_dup(const int fd1, const int fd2) {
    std::stack<int> fd_stack;
    if (fd1 == fd2)
    {
        return fd2;
     } else {
         int fd_now = 0;
         while(true) {
             fd_now = dup(fd1);
             if(fd_now != fd2) {
                 fd_stack.push(fd_now);
                 continue;
             }
         }
     }
     while(!fd_stack.empty()) {
        int temp = fd_stack.top();
        fd_stack.pop();
        close(temp);
     }
     return fd2;
}
上一篇 下一篇

猜你喜欢

热点阅读