Samuel
Samuel

Reputation: 851

Why DeviceIoControl sometimes not working (error=2)?

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");
}

I restart the program and about 95% DeviceIoControl will get the error 2 and 5% get the correct result....

I can not reproduce the error for another machine because this code is 100% working on my laptop (win10).

My target OS is Windows Server 2016.

Upvotes: 0

Views: 1056

Answers (1)

Strive Sun
Strive Sun

Reputation: 6299

The disk performance counters in Windows Server 2016 are turned off by default.

You can run CMD as admin and enter diskperf -Y to enable the disk counter of the task manager.

enter image description here

Upvotes: 6

Related Questions