文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>小研究一下dup()函数

小研究一下dup()函数

时间:2006-11-11  来源:longtem

手册:
       #include <unistd.h>

       int dup(int fildes);
       int dup2(int fildes, int fildes2);

       dup, dup2 - duplicate an open file descriptor

       RETURN VALUE
       Upon successful completion a non-negative  integer,  namely  the  file
       descriptor,  shall  be  returned;  otherwise, -1 shall be returned and
       errno set to indicate the error.


其实,dup可用dup2取代,方式:

fda=dup(fdb)  <=>dup2(fdb,fda)
所以以下的讨论只用dup2()

实验用的函数:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#define PTHA "/dev/shm/testa"
#define PTHB "/dev/shm/testb"

int main()
{
  int fda,fdb;
  int fdtmp; //to save fdb

  fdb=open(PTHB,O_CREAT | O_RDWR,0666);
  fda=open(PTHA,O_CREAT | O_RDWR,0666);
  dup2(fdb,fdtmp);
  dup2(fda,fdb); //make fdb=fda

  write(fda,"throute fda",11);//all goes to fda
  write(fdb,"throute fdb",11);//all goes to fda
  dup2(fdtmp,fdb);//restore
  write(fdb,"after invoke",12);//all goes to fdb now

  return 0;
}

功能利用,输出重定向:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#define PTHA "/dev/shm/testa"

int main()
{
  int fda;

  fda=open(PTHA,O_CREAT | O_RDWR,0666);
  dup2(fda,STDOUT_FILENO); //re-direct stdout

  system("ls");

  close(fda);

  return 0;
}

执行完生成的程序后,会发现/dev/shm/testa里含有ls命令的输出
相关阅读 更多 +
排行榜 更多 +
锤击

锤击

休闲益智 下载
穿越时空的猫里奥

穿越时空的猫里奥

动作格斗 下载
麻匪动态壁纸

麻匪动态壁纸

主题美化 下载