您的位置:首页 > 其它

dup2 redirect stdout stderr

2016-04-06 22:33 471 查看
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
void main() {
int fd;
fd = open("/tmp/leo.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
if(fd < 0) {
fd = open("/dev/null", O_WRONLY);
}
//    dup will not success
//    dup(fd, 1);
//    dup(fd, 2);
dup2(fd, 1);
dup2(fd, 2);
close(fd);
printf("test string\n");
fprintf(stderr, "test string 2\n");
}


$ ./a.out

$ cat leo.log

test string 2

test string

------------- 使用dup的情况:-----------

$ ./a.out

test string

test string 2

Advanced Programming in the UNIX® Environment: UNIX File I/O
http://www.informit.com/articles/article.aspx?p=99706&seqNum=12
Linux管道编程技术:dup函数,dup2函数,open函数详解
http://blog.csdn.net/zhouhong1026/article/details/8151235
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: