zoukankan      html  css  js  c++  java
  • APUE 习题3-2 实现dup2,要求不使用fcntl函数。

    int mydup2(int oldfd, int newfd)
    {
        int tfd = 0;
        if (newfd < 0)
        {
            err_sys("newfd < 0");
        }
        if (newfd == oldfd)
        {
            return oldfd;
        }
     
        while(1)
        {
            tfd = dup(oldfd);
     
            if (tfd == newfd)
            {
                return newfd;
            }
            else if (tfd > newfd)
            {
                close(newfd);
            }
        }
    }
     
    测试:
    #include "apue.h"
    #include <fcntl.h>
     
    int mydup2(int oldfd, int newfd);
    int main(void)
    {
        int fd = 0;
        fd = open("testdup2.dat", O_RDWR | O_CREAT | O_TRUNC);
        if (fd < 0)
        {
            printf("open error. ");
            return -1;
        }
     
        if (mydup2(fd, STDOUT_FILENO) < 0)
        {
            printf("mydup2 error ");
            return -1;
        }
     
        printf("slk ");
     
        return 0;
    }
     
    int mydup2(int oldfd, int newfd)
    {
        int tfd = 0;
        if (newfd < 0)
        {
            err_sys("newfd < 0");
        }
        if (newfd == oldfd)
        {
            return oldfd;
        }
     
        while(1)
        {
            tfd = dup(oldfd);
     
            if (tfd == newfd)
            {
                return newfd;
            }
            else if (tfd > newfd)
            {
                close(newfd);
            }
        }
    }
     
    可以把输出重定向到testdup2.dat,成功
  • 相关阅读:
    flex 和bison的安装和使用
    c++ map
    C++ 值传递、址传递、引用传递
    位运算
    POJ 1185 炮兵阵地 (状压DP)
    POJ 3114 Countries in War(强联通分量+Tarjan)
    Codeforces Round #262 (Div. 2) A B C
    2014多校第十场1002 || HDU 4972 A simple dynamic programming problem
    2014多校第十场1004 || HDU 4974 A simple water problem
    POJ 1144 Network(Tarjan)
  • 原文地址:https://www.cnblogs.com/shenlinken/p/5732817.html
Copyright © 2011-2022 走看看