FILE_FLAG_DELETE_ON_CLOSE和内存映射文件 [英] FILE_FLAG_DELETE_ON_CLOSE and memory mapped files

查看:75
本文介绍了FILE_FLAG_DELETE_ON_CLOSE和内存映射文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是特别有用,但是我很好奇以下原因,仅仅是因为即使删除文件后页面仍然恰好在内存中?在这种情况下,如果换出页面,数据将会丢失吗?

Not that it's particularly useful, but I'm curious as to why the following works, is it simply because the page still happens to be in memory even after the file is deleted? In which case, if the page is swapped out the data will be lost?

#include <iostream>
#include <memory>
#include <windows.h>

int main()
{
    typedef std::unique_ptr<void, decltype(&CloseHandle)> Handle;
    typedef std::unique_ptr<void, decltype(&UnmapViewOfFile)> View;

    View v(nullptr, UnmapViewOfFile);

    {
        Handle h(CreateFile(
            L"test",
            GENERIC_READ | GENERIC_WRITE,
            0,
            nullptr,
            CREATE_ALWAYS,
            FILE_FLAG_DELETE_ON_CLOSE,
            nullptr
        ), CloseHandle);

        // write something so CreateFileMapping succeeds
        DWORD sz;
        WriteFile(h.get(), "hello world", 12, &sz, nullptr);

        Handle m(CreateFileMapping(
            h.get(),
            nullptr,
            PAGE_READWRITE,
            0, 0,
            nullptr
        ), CloseHandle);

        v.reset(MapViewOfFile(
            m.get(),
            FILE_MAP_WRITE,
            0, 0,
            0
        ));

        char c;
        std::cin >> c; // File is still in folder
    }

    char c;
    std::cin >> c; // No file!

    std::cout << static_cast<char*>(v.get()); // Still writes
}

推荐答案

FILE_FLAG_DELETE_ON_CLOSE 遵循不幸的Windows传统,即将取消链接操作称为删除".实际上,仅当关闭文件时,该标志才会导致该文件从指定目录取消链接.

FILE_FLAG_DELETE_ON_CLOSE follows the unfortunate Windows tradition of referring to an unlink operation as "delete". In fact, the flag only causes the file to be unlinked from the specified directory when the file is closed.

与其他操作系统一样,Windows仅赋予普通用户代码从特定目录取消链接文件的能力.删除始终是操作系统的决定,发生在无法再以任何方式引用该文件时.

Like other operating systems, Windows only gives ordinary user code the ability to unlink a file from a particular directory. Deleting is always the operating system's decision, taking place when the file can no longer be referenced in any way.

如果您看一下,您会看到该文件实际上已从目录取消链接,但实际上不会被删除(并且数据在磁盘上所占的空间可供重用),直到其引用计数降至零.该映射具有参考.

If you look, you'll see the file has in fact been unlinked from the directory, but it will not actually be deleted (and the space the data takes on disk available for re-use) until its reference count drops to zero. The mapping holds a reference.

这篇关于FILE_FLAG_DELETE_ON_CLOSE和内存映射文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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