设为首页 加入收藏

TOP

用dup2和dup产生一份拷贝(二)
2014-04-06 17:40:38 来源: 作者: 【 】 浏览:197
Tags:dup2 dup 产生 拷贝

 

  问题都在第二个printf语句中调用的dup2

  dup2的第二个参数是1,1是什么 STDIN_FILENO宏的本质就是1.这里还是那句话“fd2 is already open, it is first closed”

  三个标准流在文件进程开始的时候肯定是都被打开的,already open是一定的事情。

  So。。。dup2非常“老实本分"的把STDOUT_FILENO在第二printf的时候关闭了

  这个时候printf的输出就不会被打印在标准输出设备上面了,因为STDOUT_FILENO已经被关闭了!!

  如果这个时候只要把第二个printf里面dup2的第二个参数改成大于2的数字就没事了。

  code:

  #include

  #include"fcntl.h"

  #include

  int main()

  {

  int file_descriptor;

  if((file_descriptor = open("./text.t",O_RDWR)) < 0)

  {

  printf("error\n");

  }

  else

  {

  printf("file descriptor is %d\n",file_descriptor);

  }

  printf("dup2 return value:%d\n dup return value\

  %d\n",dup2(file_descriptor,0),dup(file_descriptor));

  printf("dup2 return value:%d\ndup return value\

  %d\n",dup2(file_descriptor,10),dup(file_descriptor));

  printf("dup2 return value:%d\ndup return value\

  %d\n",dup2(file_descriptor,11),dup(file_descriptor));

  close(file_descriptor);

  return 0;

  }

  运行结果:

  file descriptor is 3

  dup2 return value:0

  dup return value 4

  dup2 return value:10

  dup return value 5

  dup2 return value:11

  dup return value 6

  这个时候就很清楚了。

  Similarly,the call

  dup2(fd, fd2);

  is equivalent to

  close(fd2);

  fcntl(fd, F_DUPFD, fd2);

  当然也不完全相同,不同点如下:

  1. dup2 is an atomic operation, whereas the alternate form involves two function

  calls. It is possible in the latter case to have a signal catcher called between the

  closeand the fcntlthat could modify the file descriptors. (W edescribe

  signals in Chapter 10.) The same problem could occur if a different thread

  changes the file descriptors. (Wedescribe threads in Chapter 11.)

  2. Ther eare s ome errnodifferences between dup2 and fcntl.

      

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++因子和阶乘 下一篇BrainFuck的编译器官方版发布

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: