zoukankan      html  css  js  c++  java
  • 2.2 dup和dup2

    原子操作:不可分割的操作

    原子:不可分割的最小单位

    原子操作的作用:解决竞争和冲突

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

    #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不操作,返回新文件描述符。

    /******功能:puts()打印到某个文件,而不是标准输出*****/
    #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);
    }
  • 相关阅读:
    路由器的配置
    逻辑卷
    valn配置
    交换分区和虚拟内存
    TCP和UDP
    语法练习1
    oracl通用函数
    AOP
    oracle查询操作
    Oracle中的转换函数
  • 原文地址:https://www.cnblogs.com/muzihuan/p/5266284.html
Copyright © 2011-2022 走看看