【发布时间】:2014-02-27 17:30:26
【问题描述】:
这是我的程序:
#include <stdio.h>
int main() {
FILE *logh;
logh = fopen("/home/user1/data.txt", "a+");
if (logh == NULL)
{
printf("error creating file \n");
return -1;
}
// write some data to the log handle and check if it gets written..
int result = fprintf(logh, "this is some test data \n");
if (result > 0)
printf("write successful \n");
else
printf("couldn't write the data to filesystem \n");
while (1) {
};
fclose(logh);
return 0;
}
当我运行这个程序时,我看到文件正在被创建,但它不包含任何数据。我的理解是,在将数据实际写入文件系统之前,内存中有数据缓存,以避免多个 IO 以提高性能。而且我也知道我可以在程序中调用 fsync/fdatasync 来强制同步。但是我可以从外部强制同步而不必更改程序吗?
我尝试从 Linux shell 运行 sync 命令,但它不会使数据出现在文件中。 :(
如果有人知道任何替代方法,请提供帮助。
一个有用的信息:我对此进行了更多研究,最后发现了这一点,要完全删除内部缓冲,FILE 模式可以使用int setvbuf(FILE *stream, char *buf, int mode, size_t size) 设置为_IONBF
【问题讨论】:
-
fflush(logh);男人冲洗
-
另外,请务必检查 fopen() 的返回值。
-
是的,谢谢,我知道他们,但有什么方法可以做到这一点而无需更改程序。我的意思是从shell命令或其他东西将进程的所有文件数据缓存刷新到文件系统
-
没有办法不改变程序..当它执行
while(1)时,要写入的数据仍然在程序的内存中
标签: c linux filesystems