【问题标题】:Why DeviceIoControl sometimes not working (error=2)?为什么 DeviceIoControl 有时不工作(错误=2)?
【发布时间】:2020-10-21 03:29:30
【问题描述】:
DISK_PERFORMANCE DiskPerformance = {0};

DWORD dwDiskInfoSize = 0;

for (int i = 0; i < 10; i++)
{

    std::printf("Try %d th Open \\\\.\\c:\n", i);

    HANDLE hDevice = CreateFile(L"\\\\.\\c:",
                                0,
                                FILE_SHARE_READ | FILE_SHARE_WRITE,
                                //SYNCHRONIZE | FILE_READ_ATTRIBUTES,
                                NULL,
                                OPEN_EXISTING,
                                0,
                                NULL);
    std::printf("hDevice = %p\n", hDevice);

    if (hDevice == INVALID_HANDLE_VALUE)
    {
        std::printf("CreateFile failed  = %d \n", GetLastError());

        continue;
    }

    if (!DeviceIoControl(hDevice,
                         IOCTL_DISK_PERFORMANCE,
                         NULL,
                         0,
                         &DiskPerformance,
                         sizeof(DiskPerformance),
                         &dwDiskInfoSize,
                         NULL))
    {

        CloseHandle(hDevice);

        std::printf("DeviceIoControl failed  = %d \n", GetLastError());

        continue;
    }

    std::printf("QuDeviceIoControlery Success\n");

    CloseHandle(hDevice);

    Sleep(1000);

    std::printf("\n\n");
}

我重新启动程序,大约 95% 的 DeviceIoControl 会得到 error 2,而 5% 会得到正确的结果....

我无法在另一台机器上重现该错误,因为此代码 100% 在我的笔记本电脑 (win10) 上运行。

我的目标操作系统是 Windows Server 2016。

【问题讨论】:

  • 除非log_sys() 抛出异常或终止进程,否则如果CreateFile() 失败,您将使用无效句柄调用DeviceIoControl()
  • 但是 CreateFile 成功
  • 即便如此,它仍然是您的代码中需要修复的错误。
  • @RemyLebeau 如果 CreateFile() 失败,我会添加“return”,但我的问题没有解决。
  • 是的,我可以重现您的问题。我将与相关工程师讨论并在此处更新结果。

标签: c++ windows winapi visual-c++


【解决方案1】:

Windows Server 2016 中的磁盘性能计数器默认关闭。

您可以以管理员身份运行CMD并输入diskperf -Y以启用任务管理器的磁盘计数器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 2019-04-01
    • 2020-11-04
    • 1970-01-01
    相关资源
    最近更新 更多