使用FSCTL_LOCK_VOLUME锁定驱动器

Locking a drive with FSCTL_LOCK_VOLUME

本文关键字:锁定 驱动器 VOLUME LOCK FSCTL 使用      更新时间:2023-10-16

我有麻烦锁定我的C驱动器,所以我可以提取一些文件信息以后。

#define wszDrive L"\\.\PhysicalDrive0"
HANDLE targetVol = INVALID_HANDLE_VALUE;
DWORD stats;
targetVol = CreateFile(wszDrive,
        0,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_EXISTING,
        /*FILE_FLAG_NO_BUFFERING | FILE_FLAG_RANDOM_ACCESS*/0,
        NULL);
    if (targetVol == INVALID_HANDLE_VALUE)    // cannot open the drive
    {
        cout << "error in ioControl with volume handler" << endl;
        system("pause");
    }
    if (DeviceIoControl(targetVol,
        FSCTL_LOCK_VOLUME,
        NULL, 0, NULL, 0,
        &stats,
        NULL) ==0)
    {
        cout << "Error with targetVol DeviceIo" << endl;
        ErrorExit(TEXT("GetProcessId"));
        system("pause");
    }

下面的错误退出返回"GetProcessID失败,错误1:不正确的函数"。

void ErrorExit(LPTSTR lpszFunction)
{
    // Retrieve the system error message for the last-error code
    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError();
    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR)&lpMsgBuf,
        0, NULL);
    // Display the error message and exit the process
    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
        (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
    StringCchPrintf((LPTSTR)lpDisplayBuf,
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"),
        lpszFunction, dw, lpMsgBuf);
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
    ExitProcess(dw);
}

你们知道发生了什么事吗?

FSCTL_LOCK_VOLUME的MSDN文档马上说

锁定未使用的卷

C:驱动器几乎总是在使用。