c++ - 在 LockFileEx 之后调用 ReadFile 时崩溃

标签 c++ c winapi

我有几个进程试图读写同一个文件。我希望他们每个人都锁定该文件,以便一次只有他们中的一个人访问它。

我试过了(编辑:这次是完整的测试代码):

#include "stdafx.h"
#include "Windows.h"


bool test()
{
        const char* path = "test.txt";

        HANDLE hFile = CreateFileA(path,
                        GENERIC_READ | GENERIC_WRITE,
                        FILE_SHARE_READ | FILE_SHARE_WRITE,
                        NULL,
                        OPEN_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);

        if (hFile == INVALID_HANDLE_VALUE)
        {
                printf("ERROR: Cannot open file %s\n", path);
                return false;
        }

        // Lock the file
        {
                OVERLAPPED overlapped = {0};
                BOOL res = LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK, 0, ~0, ~0, &overlapped);
                if (!res)
                {
                        printf("ERROR: Cannot lock file %s\n", path);
                        return false;
                }
        }

        DWORD fileSize = GetFileSize(hFile, NULL);
        if (fileSize > 0)
        {
                char* content = new char[fileSize+1];

                // Read the file
                BOOL res = ReadFile(hFile, content, fileSize, NULL, NULL);
                if (!res)
                {
                        printf("ERROR: Cannot read file %s\n", path);
                }

                delete[] content;
        }


        const char* newContent = "bla";
        int newContentSize = 3;

        // Write the file
        BOOL res = WriteFile(hFile, newContent, newContentSize, NULL, NULL);
        if (!res)
        {
                //int err = GetLastError();
                printf("ERROR: Cannot write to file\n");
        }

        // Unlock the file
        {
                OVERLAPPED overlapped = {0};
                UnlockFileEx(hFile, 0, ~0, ~0, &overlapped);
        }

        CloseHandle(hFile);

        return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
        bool res = test();

        return 0;
}

这在我的 Windows 8 电脑上运行良好。但是在我同事的 Windows 7 电脑上,它崩溃了。具体来说,对 ReadFile 和 WriteFile 的调用总是崩溃。

请注意,它永远不会进入带有错误 printfs 的代码路径。此代码不会触发任何错误,除了在 ReadFile 中的位置 0x00000000 处写入(在 Windows 7 上运行时)。

我们还尝试将重叠结构传递给 ReadFile 和 WriteFile 调用。它可以防止崩溃,但锁不再起作用,文件全部被加扰(不是用这个测试代码,用真实代码)。

我做错了什么?

最佳答案

看起来你的问题是:

lpNumberOfBytesRead [out, optional] 参数在您的调用中为空。

只有当 lpOverlapped 参数为 NULL 时,该参数才能为 NULL。

http://msdn.microsoft.com/en-us/library/windows/desktop/aa365467%28v=vs.85%29.aspx

关于c++ - 在 LockFileEx 之后调用 ReadFile 时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27687323/

相关文章:

c# - 尝试获取客户端进程可执行路径时访问被拒绝错误

c++ - C++ 中用于计划任务的 Win32 函数

C++ 使用 operator int() 而不是 operator+

c++ - 在 GTEST (Googletest) 中使用模板

c - 关于整数格式转换

c - 使用 PIC 微 Controller 控制直流电机的嵌入式 C 代码

c - 从 C 代码生成程序的多个副本并将输出重定向到文件

c++ - MailSlot写发送同样的东西三次C/C++

c++ - istream_iterator 和惰性求值

c++ - 关于延迟动态初始化的问题