linux编程-文件操作(4)

来源:互联网 发布:软件instagram下载 编辑:程序博客网 时间:2024/06/04 20:20

文件描述符号拷贝dup

一、接口说明

#include <unistd.h>

 

int dup(int oldfd);

int dup2(int oldfd, int newfd);

 

#define _GNU_SOURCE             /* See feature_test_macros(7) */

#include <fcntl.h>                       /*Obtain O_* constant definitions */

#include <unistd.h>

 

int dup3(int oldfd, int newfd, int flags);

 

 

非原子操作

int fdDup3 = 101;

Close(fdDup3)

fdTmp = fcntl(fdLog, F_DUPFD, fdDup3);

 

备注:

Dup在拷贝文件描述符时,会清除close-on-exec

api接口说明可通过man dup查询


二、代码案例

         intfdDup1 = dup(fdLog);

         if(fdDup1 != -1)

         {

                   ReadFile(fdDup1);

                   close(fdDup1);

         }

         intfdDup2 = 100;

         intfdTmp = dup2(fdLog, fdDup2);

         if(fdTmp != fdDup2)

         {

                   printf("Copyfd to 100 failed");

         }

         else

         {

                   ReadFile(fdDup2);

                   close(fdDup2);

         }

        

         intfdDup3 = 101;

         fdTmp= fcntl(fdLog, F_DUPFD, fdDup3);

         if(fdTmp != fdDup3)

         {

                   printf("Copyfd to 100 failed");

         }

         else

         {

                   ReadFile(fdDup3);

                   close(fdDup3);

         }


 三、执行结果


0 0
原创粉丝点击