首页 > 其他 > 详细

dup和dup2

时间:2016-03-11 16:59:20      阅读:282      评论:0      收藏:0      [点我收藏+]

功能:复制一个文件描述符

#include <unistd.h>

int dup(int oldfd);

int dup2(int oldfd , int newfd);

dup:不是原子操作

dup2:是原子操作

If oldfd is not a valid file descriptor, then the call fails, and newfd is not closed.

当旧fd不是一个有效的文件描述符,那么调用失败,新的描述符不会关闭。

If oldfd is a valid file descriptor, and newfd has the same value as oldfd, then dup2() does nothing,and returns newfd.

当旧fd是个有效的描述符,新描述符和旧文件描述符值相同,但么dup2不操作,返回新文件描述符。

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define FNAME   "/tmp/out"

int main()
{
    int fd ;
    fd = open(FNAME , O_WRONLY | O_CREAT | O_TRUNC ,0600);
    if(fd < 0)
    {
        perror("open()");
        exit(1);
    }
    /******非原子操作*****/
    //close(1);
    //dup(fd);    
    /********原子操作******/
    dup2(fd , 1 );
    if(fd !=1)
        close(fd);
    puts("hello");
    exit(0);
}

 

dup和dup2

原文:http://www.cnblogs.com/muzihuan/p/5266284.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!