加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

linux c 使用dup2函数将输出重定向到文件 --execl

(2009-10-30 13:56:51)
标签:

dup2

execl

分类: LINUX

 

一个实际应用的例子:
            char std_file[PATH_MAX + 1];
            FILE *std_fp;
            if((std_fp = fopen(
"/home/hy/out.std","w+")) == NULL){
               
do_log(".....\n");
                exit(6);
            }
            if(dup2(fileno(std_fp),STDOUT_FILENO) == -1){
                do_log(".....\n");
                fclose(std_fp);
                exit(5);
            }
            if(dup2(fileno(std_fp),STDERR_FILENO) == -1){
               
do_log(".....\n");
                fclose(std_fp);
                exit(5);
            }
            fclose(std_fp);
            execl( EXE_PATH, EXE_NAME, ..... NULL ); //启动命令,省略


 

在我的实际应用中,因为fork了一个子进程,所以要考虑输出的信息怎样保存到文件中,所以使用了这个。

函数的其他东西可以参考以下资料

----------------------------------------------------------------------------------

#include <unistd.h>
int dup( int filedes );
int dup2( int filedes, int filedes2 );  //
新文件描述符filedes,并且将filedes2新文件描述符的

//dup
函数的作用:制一个有的句柄,生一个与源句柄特性完全一的新句柄
//   
(也即生成一个新的句柄号,并
关联到同一个设备,而且它返回的一定是当前可用的
//   
文件描述符中的最小数


//dup2
函数的作用:
制一个有的句柄到另一个句柄上,目句柄的特性与源句柄特性
//   
完全一
(也即首先关闭句柄,与设备,接着从源句柄完全拷贝复制到目句柄)


//  
些函数返回的新文件描述符与参数filedes2共享同一个文件表

//dupdup2都是系window平台对应DuplicateHandle函数

 

 

#include <io.h>

#include <stdlib.h>

#include <stdio.h>

 

void main( void )

{

   int old;

   FILE *new;

 

   old = _dup( 1 );  

                     

   if( old == -1 )

   {

      perror( "_dup( 1 ) failure" );

      exit( 1 );

   }

   write( old, "This goes to stdout first\r\n", 27 );

   if( ( new = fopen( "data", "w" ) ) == NULL )

   {

      puts( "Can't open file 'data'\n" );

      exit( 1 );

   }

 

  

   if( -1 == _dup2( _fileno( new ), 1 ) )

   {

      perror( "Can't _dup2 stdout" );

      exit( 1 );

   }

   puts( "This goes to file 'data'\r\n" );

 

  

   fflush( stdout );

   fclose( new );

 

  

   _dup2( old, 1 );

   puts( "This goes to stdout\n" );

   puts( "The file 'data' contains:" );

   system( "type data" );

------------------------------------------------------------------------------------------------------------------------------------



0

阅读 收藏 喜欢 打印举报/Report
前一篇:秋风,落叶
后一篇:fileno的作用
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有