分类: LINUX
2010-11-15 20:22:00
fd = dup(1);//1-标准输出,对文件描述符fd的操作将输出至标准输出.
int main(void){
int fd = -1;
int fd2 = -1;
fd = open("/tmp/dup",O_RDWR | O_CREAT,0644);
if(fd < 0){
printf("open /tmp/dup file faile!\n");
}
#if 0
fd = dup(1);//对fd的操作,数据直接重定向到标准输出
write(fd,"this is a test!\n",16);
printf("Begin:Write these to stdout!\n");
fprintf(stdout,"Write second strings!\n");
close(fd);
#endif
dup2(fd,1);//对标准输入的操作将数据直接输入到文件描述符fd
// 对应的文件中去。
write(fd,"this is a test!\n",16);
printf("Writer to /tmp/dup file!\n");
close(fd);
printf("close fd\n");// 这行会显示在哪里呢,当然是自己建立的
//文件中,因为标准输出和fd共享一个文件表(File Table)
close(1);
printf("close stdout!!\n");//不会有任何显示
return 0;
}
========================================================
cat /tmp/dup
this is a test!
Writer to /tmp/dup file!
close fd
========================================================
以上是我对它们的一点理解吧,有不对的地方望大牛们多多指点 ^ ^