支持HW团队,就支付宝领取下面的红包吧!(2018年3月31前,就几毛,也会几块,可以和其他红包叠加使用),你领取消费,HW有奖励。红包使用无条件限制,有条件请注意是不是有病毒。

小伙伴们,给大家发红包喽!人人可领,领完就能用。祝大家领取的红包金额大大大!#吱口令#长按复制此消息,打开支付宝就能领取!er1OEj73Uj

登入 注册 | 验证
| 搜索
HelloWorld论坛 : > 计算机科学、技术、教学> 编程入门> c、c++基础> [转]linux C使用execl函数重定向问题(dup和dup2函数的作用)
 
 
 
 
类别:c++ 阅读:6323 评论:0 时间:十二月 13, 2012, 5:14 a.m. 关键字:

 

 来源:http://yonghan.blog.sohu.com/94105721.html

dup和dup2函数的作用

#include <unistd.h>
int dup( int filedes );
int dup2( int filedes, int filedes2 ); //新文件描述符复制filedes,并且将filedes2值作为新文件描述符的值
//dup函数的作用:复制一个现有的句柄,产生一个与“源句柄特性”完全一样的新句柄
// (也即生成一个新的句柄号,并关联到同一个设备,而且它返回的一定是当前可用的
// 文件描述符中的最小数值)


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

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

//dup和dup2都是系统服务,window平台对应DuplicateHandle函数

/* DUP.C: This program uses the variable old to save

* the original stdout. It then opens a new file named

* new and forces stdout to refer to it. Finally, it

* restores stdout to its original state.

*/

#include <io.h>

#include <stdlib.h>

#include <stdio.h>

 

void main( void )

{

int old;

FILE *new;

 

old = _dup( 1 ); /* "old" now refers to "stdout" */

/* Note: file handle 1 == "stdout" */

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 );

}

 

/* stdout now refers to file "data" */

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

{

perror( "Can't _dup2 stdout" );

exit( 1 );

}

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

 

/* Flush stdout stream buffer so it goes to correct file */

fflush( stdout );

fclose( new );

 

/* Restore original stdout */

_dup2( old, 1 );

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

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

system( "type data" );

}

自己的实例:

 

int old;

FILE *new;

 

old = dup( 1 );

if( ( new = fopen( "/home/hy/0516/ilm/ilmsched/aaa.log", "w" ) ) == NULL )

{

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

exit( -1 );

}

if( -1 == dup2( fileno( new ), 1 ) )

{

perror( "Can't _dup2 stdout" );

exit( 1 );

}

 

 

 

execl( "/home/hy/0516/ilm/ilmassess/ilmassess", "ilmassess", "/home/hy",

"-mode", "both",

"-logdir", "/home/hy/ilm/ilmassess/", "-logfile",

"ilmassess.log", "-errfile",

"ilmassess_err.log", "-parfile",

"/home/hy/0516/ilm/ilmassess/ilmassess_option",NULL);

 

fflush( stdout );

fclose( new );

[挂载人]初学MPEG [审核人]初学MPEG 推荐

个人签名--------------------------------------------------------------------------------

Please Login (or Sign Up) to leave a comment