代码一:
int main(){ int fd = open("/home/lrao/test", O_CREAT | O_RDWR | O_APPEND, S_IRWXU|S_IRWXG|S_IRWXO) ; close(1) ; int fd2 = dup(fd) ; printf("hello"); write(fd,"\r\nwrite\r\n",9); write(fd2,"\r\nwrite\r\n",9); close(fd); return 0; }
运行结果:(文件里的内容)
write
write
hello
代码二:
int main(){ int fd = open("/home/lrao/test", O_CREAT | O_RDWR | O_APPEND, S_IRWXU|S_IRWXG|S_IRWXO) ; close(1) ; fd= dup(fd) ; printf("hello"); write(fd,"\r\nwrite\r\n",9); close(fd); return 0; }运行结果:(文件里的内容)
write
(注意,里面没有hello)
#include <unistd.h>
int dup(int oldfd);
int dup2(int oldfd, int newfd);
RETURN VALUE
On success, these system calls return the new descriptor. On error, -1
is returned, and errno is set appropriately.
(正在求解.......)
代码三:
int main(){ int fd = open("/home/lrao/coding/unix/test", O_CREAT | O_RDWR | O_APPEND, S_IRWXU|S_IRWXG|S_IRWXO) ; close(1) ; int fd2 = dup(fd) ; printf("hello"); write(fd,"\r\nwrite\r\n",9); write(fd2,"\r\nwrite\r\n",9); close(fd); close(fd2); return 0; }运行结果:(文件里的内容)
非常高兴,
原因明显了:
代码一中:并没有文件打开计数是 2 ,但我只有一次close ,对于代码二中,发现,我文件打开计数引用为 1 ,在程序结束前,我将其关闭了,而printf的内容在缓冲区里,缓冲区未满,只有在程序结束的时候,才写入文件中去!
下面代码来难验证一下,我刚刚的结论:我们把代码三 拿来改改
代码四:
int main(){ int fd = open("/home/lrao/coding/unix/test", O_CREAT | O_RDWR | O_APPEND, S_IRWXU|S_IRWXG|S_IRWXO) ; close(1) ; int fd2 = dup(fd) ; char buf[1024*5] ; memset(buf,65,1024*5); buf[1024*5-1] =0; printf("hello:%s\r\nhello",buf); write(fd,"\r\nwrite\r\n",9); write(fd2,"\r\nwrite\r\n",9); close(fd); close(fd2); return 0; }
ls -lk
发现在
-rwxrwxr-x. 1 lrao lrao 6 Oct 24 19:06 test
test 大小变成了6K,明显printf写入文件了