为什么在进程退出时数据不会被刷新到文件? [英] Why is data not being flushed to file on process exit?

查看:376
本文介绍了为什么在进程退出时数据不会被刷新到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  int main(int argc,char * argv [])
{
FILE * fp = fopen(a.txt,wt);

fprintf(fp,AAAA);

//不需要刷新。并没有关闭
raise(SIGTERM);

exit(EXIT_SUCCESS);

$ / code>

结果:没有数据写入到a.txt



我预计这很好。因为系统将关闭文件句柄,然后文件系统驱动程序在其Close处理程序中刷新未刷新的数据。但事实并非如此。
我在EXT4上测试了这个代码,ubuntu 11.10问题:
我以为所有的文件系统都必须在关闭处理时刷新未刷新的数据。
Posix没有规则?



PS此代码在NTFS,Win7上运行良好(刷新良好)

  int _tmain(int argc,_TCHAR * argv [])
{
HANDLE h = CreateFile(LD:\\ a。 txt,GENERIC_READ | GENERIC_WRITE,
0,0,OPEN_ALWAYS,0,0);
BYTE a [3];
memset(a,'A',3);
DWORD dw;
WriteFile(h,(PVOID)a,3,& dw,0);

TerminateProcess(GetCurrentProcess(),1);
返回0;

编辑:

我再次用系统调用 write 来测试它。它被冲洗得很好。

  int main(int argc,char ** argv)
{
int fd = open( a.txt,O_CREAT | O_TRUNC | O_WRONLY);
char buf [3];
memset(buf,'A',3);
size_t result = write(fd,buf,3);

raise(SIGTERM);
exit(EXIT_SUCCESS);
返回0;


解决方案

与文件系统驱动程序有关。问题是CRT正在缓冲文件流本身。你用setvbuf()设置缓冲区大小,如果你不使用这个函数,它使用默认值。当使用WriteFile()时,应用程序中没有缓冲区,输出缓冲在操作系统的文件系统缓存中。免于突然的应用程序中止。

您必须调用fflush()来实现相同的功能。


int main(int argc, char *argv[])
{
    FILE *fp = fopen("a.txt", "wt");

    fprintf(fp, "AAAA");

    // No flush. and No close
    raise(SIGTERM);

    exit(EXIT_SUCCESS);
}

result: No data has written to a.txt

I expected this is fine. Because the system will close the file handle and then the filesystem driver flushes the unflushed data in his Close handler. But it wasn't. I tested this code on EXT4, ubuntu 11.10

Question: I thought ALL filesystems must flush unflushed data at his close processing.
Posix doesn't have the rule?

P.S This code worked well (flushed well) on NTFS, Win7

int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE h = CreateFile(L"D:\\a.txt", GENERIC_READ|GENERIC_WRITE,
        0, 0, OPEN_ALWAYS, 0, 0);
    BYTE a[3];
    memset(a, 'A', 3);
    DWORD dw;
    WriteFile(h, (PVOID)a, 3, &dw, 0);

    TerminateProcess(GetCurrentProcess(), 1);
    return 0;
}

Edit:
I tested it again with system call write. And it was flushed well.

int main(int argc, char** argv)
{
    int fd = open("a.txt", O_CREAT|O_TRUNC|O_WRONLY);
    char buf[3];
    memset(buf, 'A', 3);
    size_t result = write(fd, buf, 3);

    raise(SIGTERM);
    exit(EXIT_SUCCESS);   
    return 0;
}

解决方案

It doesn't have anything to do with file system drivers. The issue is that the CRT is buffering the file stream itself. You set the buffer size with setvbuf(), it uses a default if you don't use this function. There's no buffering in the application when you use WriteFile(), output is buffered in the operating system's file system cache. Immune from abrupt app aborts.

You'll have to call fflush() to achieve the same.

这篇关于为什么在进程退出时数据不会被刷新到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆