码迷,mamicode.com
首页 > 其他好文 > 详细

dup和dup2

时间:2016-03-11 17:01:27      阅读:186      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!