#include
int dup2(int oldfd, int newfd);
The error returned by dup2() is different from that returned by fcntl(..., F_DUPFD, ...) when newfd is out of range. On some systems dup2() also sometimes returns EINVAL like F_DUPFD.
If newfd was open, any errors that would have been reported at close(2) time are lost. A careful programmer will not use dup2() or dup3() without closing newfd first.
dup2函数的作用就是文件描述符重定向的作用。
例如下面的程序:将stdout重定向到一个指定的文件描述符中。
- #include <iostream>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include <fcntl.h>
- #include <unistd.h>
- using namespace std;
- int main()
- {
- FILE *fp = NULL;
- int fd1;
- fprintf( stdout, "[%d]dup2 test\n", __LINE__ );
- fd1 = open( "dup2.txt", (O_RDWR), 0644 );
- if( fp < 0 )
- {
- printf( "[%d]fopen error=[%s]\n", __LINE__, strerror(errno) );
- return 1;
- }
- if( dup2( fd1, 1 ) < 0 )
- {
- printf( "[%d]dup2 error=[%s]\n", __LINE__, strerror(errno) );
- }
- close( fd1 );
- fprintf( stdout, "[%d]dup2 test\n", __LINE__ );
- fprintf( stdout, "[%d]dup2 test\n", __LINE__ );
- }
- ~
也可参考如下文章。
阅读(1394) | 评论(0) | 转发(0) |