UNIX重定向--dup(2)函数

用同一个open()翻开的文件能够有多个描绘字与它相连,这种描绘字称为重复描绘字。重复一个描绘字有两种办法:用函数dup()或dup2(),或用函数fcntl()。 #include  int dup (int old); int dup2 (int old,int new); dup()仿制描绘字old至一个新描绘字,新描绘字确保是当时未翻开的最小编号可用描绘字。dup2() http://www.star1111.info/linked/20130312.do 仿制描绘字old至编号为new的描绘字。若是new现已翻开,它将首要被封闭。若是new等于old,dup2()回来new但不封闭它。 这两个函数调用成功回来新的文件描绘字。所回来的新描绘字与参数old给定的描绘字引证同一个翻开的文件,即同享同一个体系翻开文件表项 在这个图示中,假定进程一开始便履行 newfd = dup(1); 因而newfd的值一定是3(由于描绘字0、1、2现已由shell翻开),它与描绘字1都指向规范输出文件,由于它的进程翻开文件表项由描绘字1的表项仿制而来。 正由于重复描绘字同享同一个体系翻开文件表项,因而,它们同享文件方位和一组文件状况标签。可是它们都有个人的文件描绘字标签。这两个dup函数总是铲除新描绘字中的履行即封闭标签FD_CLOEXEC。 重复一个文件描绘字的主要用途是完成输入输出重定向,即改动一个特定文件描绘字对应的文件或管道。当运用管道进行进程间的通讯时,这两个函数非常有用。第11章评论进程间通讯时将见到使用这两个函数的比如。  下面这个程序是用dup2()简略重定向的比如。它将规范输出文件重定向至名为myoutput的文件。运转这个程序能够看到printf()的输出不在终端而在文件myoutput中。 int main(void)
{
   int fd;
   if((fd = open("myoutput",O_WRONLY|O_CREAT,0644)) == -1)
      err_exit("myoutput");
   if(dup2(fd,STDOUT_FILENO) == -1)    /* 重复规范输出至fd相连的文件myoutput */
      err_exit("Redirect standard output failed");
   printf("this is a test program for redirect \n");
   close(fd);
} 下面给出一个关于dup、dup2 文件描绘符重定向函数的程序  #include 
#include 
#include 
#include 
int main(void)
{
   #define STDOUT 1   //规范输出文件描绘符 号
   int nul, oldstdout;
   char msg[] = "This is a test";
   /* create a file */
//翻开一个文件,操作者具有读写权限 若是文件不存在就创立
   nul = open("DUMMY.FIL", O_CREAT | O_RDWR,
      S_IREAD | S_IWRITE);
   /* create a duplicate handle for standard
      output */
//创立STDOUT的描绘符备份
   oldstdout = dup(STDOUT);
   /*
      redirect standard output to DUMMY.FIL
      by duplicating the file handle onto the
      file handle for standard output.
   */
//重定向STDOUT到nul
   dup2(nul, STDOUT);
   /* close the handle for DUMMY.FIL */
//重定向之后要封闭nul
   close(nul);
   /* will be redirected into DUMMY.FIL */
//写入数据
   write(STDOUT, msg, strlen(msg));
   /* restore original standard output
      handle */
//复原
   dup2(oldstdout, STDOUT);
   /* close duplicate handle for STDOUT */
   close(oldstdout);
   return 0;
}
//成果就是msg写到了文件中而不是STDOUT http://www.fpzhuhai.com/linked/20130312.do 
posted @ 2013-03-13 10:03  chinadiy197601  阅读(188)  评论(0编辑  收藏  举报