先上一段正常的代码,如下:
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int oldfd = open("mytest",O_RDWR | O_CREAT,0644);
dup2(oldfd,1);
close(oldfd);
printf("hello world\n");
return 0;
}
编译,运行,结果正常, hello world 被重定向到了文件。
接着 给代码 加上一个 死循环,让 hello world 不断的写入重定向的文件。代码如下:
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int oldfd = open("mytest",O_RDWR | O_CREAT,0644);
dup2(oldfd,1);
close(oldfd);
while(1)
printf("hello world\n");
return 0;
}
编译,运行,然后查看 mytest 文件,发现 hello world 在不断的写入,也是正常的。然后,加上一个 sleep 出现问题了。(先删除 mytest 文件,然后修改代码)。代码如下:
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int oldfd = open("mytest",O_RDWR | O_CREAT,0644);
dup2(oldfd,1);
close(oldfd);
while(1){
sleep(1);
printf("hello world\n");
}
return 0;
}
这个时候再编译运行,然后使用 cat 查看 mytest 文件,发现没有内容。 ls -l 查看 发现文件大小为0