Click here to Skip to main content
13,866,036 members
Click here to Skip to main content
Add your own
alternative version


69 bookmarked
Posted 21 Jul 2007
Licenced CPOL

Get Process Info with NtQueryInformationProcess

, 21 Jul 2007
Rate this:
Please Sign up or sign in to vote.
Get process parent ID, command-line, etc.

Screenshot - GetNtProcessInfo.png


This article will show a method to read the following items of a process, primarily using the NtQueryInformationProcess() and ReadProcessMemory() functions:

  • Process ID
  • Parent ID
  • Affinity Mask
  • Exit Code Status
  • Command Line of Process
  • Path of Process Image File
  • Terminal Services Session ID
  • Flag, if process is currently under debugging
  • Address of Process Environment Block (PEB)

This information is returned in a variable declared as a structure, smPROCESSINFO. This structure is defined in NtProcessInfo.h:

typedef struct _smPROCESSINFO
    DWORD   dwPID;
    DWORD   dwParentPID;
    DWORD   dwSessionID;
    DWORD   dwPEBBaseAddress;
    DWORD   dwAffinityMask;
    LONG    dwBasePriority;
    LONG    dwExitStatus;
    BYTE    cBeingDebugged;

Although there are Windows APIs to retrieve most of the values above, this article will show how to obtain those values while getting those not available through Windows APIs. Note: this method uses structures and functions in the core NTDLL.DLL, which could change in future versions. Microsoft recommends using Windows APIs to "safely" obtain information from the system.

The core functions to retrieve the above information are provided in NtProcessInfo.h and NtProcessInfo.cpp. Just include these into your project h/cpp files, reference the functions, and compile. If you include these files in your project/solution list, don't forget to exclude them from the build. The main function, sm_GetNtProcessInfo(), requires a process ID and a variable declared as smPROCESSINFO. I recommend calling the functions in the order below (step 5 and 6 could be swapped):

  1. sm_EnableTokenPrivilege or your custom token privilege function to enable SE_DEBUG_NAME.
  2. sm_LoadNTDLLFunctions. Keep the HMODULE variable returned to free the library later.
  3. Get the process ID. Either specify one manually, or use EnumProcesses, GetCurrentProcessId, CreateToolhelp32Snapshot, etc.
  4. sm_GetNtProcessInfo with process ID and the smPROCESSINFO variable.
  5. Output the contents of your smPROCESSINFO variable/array to your desired medium.
  6. sm_FreeNTDLLFunctions with the HMODULE variable returned from sm_LoadNTDLLFunctions.

The demo application with this article is a basic Win32, with a ListView common control child window to list the process contents. The code was also used with no problem within an MFC application. This code was written in Visual Studio .NET 2003 SP1, and is intended for Win2K or later.

Enable Debug Privilege

In order for the current user to read information for most processes, we must enable the debug privilege. The user token or the group token the user belongs to must already have the debug privilege assigned. To determine which privileges a token has, use the GetTokenInformation() function. For our function, we pass SE_DEBUG_NAME as the parameter, and if the function successfully enables the privilege, it will return TRUE.

BOOL sm_EnableTokenPrivilege(LPCTSTR pszPrivilege)
    HANDLE hToken        = 0;
    TOKEN_PRIVILEGES tkp = {0}; 

    // Get a token for this process.

    if (!OpenProcessToken(GetCurrentProcess(),
                          TOKEN_ADJUST_PRIVILEGES |
                          TOKEN_QUERY, &hToken))
        return FALSE;

    // Get the LUID for the privilege. 

    if(LookupPrivilegeValue(NULL, pszPrivilege,
        tkp.PrivilegeCount = 1;  // one privilege to set    

        tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

        // Set the privilege for this process. 

        AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
                              (PTOKEN_PRIVILEGES)NULL, 0); 

        if (GetLastError() != ERROR_SUCCESS)
           return FALSE;
        return TRUE;

    return FALSE;

Enumerate the Process IDs

To get a list of running processes, we will use the Process Status API, EnumProcesses(). There are several ways to get process IDs. A few are mentioned above in the introduction. With a process ID, we call the sm_GetNtProcessInfo() function to fill our smPROCESSINFO variable. For the sake of the demo, I limited the array to 50 processes (defined as MAX_PI).

DWORD EnumProcesses2Array(smPROCESSINFO lpi[MAX_PI])
    DWORD dwPIDs[MAX_PI] = {0};
    DWORD dwArraySize    = MAX_PI * sizeof(DWORD);
    DWORD dwSizeNeeded   = 0;
    DWORD dwPIDCount     = 0;

    //== only to have better chance to read processes =====

        return 0;

    // Get a list of Process IDs of current running processes

    if(EnumProcesses((DWORD*)&dwPIDs, dwArraySize, &dwSizeNeeded))
        HMODULE hNtDll = sm_LoadNTDLLFunctions();

            // Get detail info on each process

            dwPIDCount = dwSizeNeeded / sizeof(DWORD);
            for(DWORD p = 0; p < MAX_PI && p < dwPIDCount; p++)
                if(sm_GetNtProcessInfo(dwPIDs[p], &lpi[p]))
                      // Do something else upon success


    // Return either PID count or MAX_PI whichever is smaller

    return (DWORD)(dwPIDCount > MAX_PI) ? MAX_PI : dwPIDCount;

Access NTDLL Functions

The NtQueryInformationProcess() function does not have an import library, so we must use run-time dynamic linking to access this function in ntdll.dll. Define the function in the header, then obtain the entry point address with GetProcAddress().

typedef NTSTATUS (NTAPI *pfnNtQueryInformationProcess)(
    IN  HANDLE ProcessHandle,
    IN  PROCESSINFOCLASS ProcessInformationClass,
    OUT PVOID ProcessInformation,
    IN  ULONG ProcessInformationLength,
    OUT PULONG ReturnLength    OPTIONAL

pfnNtQueryInformationProcess gNtQueryInformationProcess;

HMODULE sm_LoadNTDLLFunctions()
    // Load NTDLL Library and get entry address

    // for NtQueryInformationProcess

    HMODULE hNtDll = LoadLibrary(_T("ntdll.dll"));
    if(hNtDll == NULL) return NULL;

    gNtQueryInformationProcess = (pfnNtQueryInformationProcess)GetProcAddress(hNtDll,
    if(gNtQueryInformationProcess == NULL) {
        return NULL;
    return hNtDll;

Get Process Basic Information

We open the process with the PROCESS_QUERY_INFORMATION access right to get basic information, and since we will use the ReadProcessMemory() function to read the PEB, the process must also be opened with the PROCESS_VM_READ access right.

// Attempt to access process

                              PROCESS_VM_READ, FALSE, dwPID);
     return FALSE;

Now, we allocate memory for our PROCESS_BASIC_INFORMATION structure variable.

// Try to allocate buffer 

hHeap = GetProcessHeap();


// Did we successfully allocate memory

if(!pbi) {
    return FALSE;

This structure is defined in both winternl.h and ntddk.h. The definition below comes from the Win2003 DDK ntddk.h, since both my winternl.h in Visual Studio 2003 and the one at Microsoft MSDN doesn't contain as much detail. I also found that winternl.h and ntddk.h conflict each other during compilation, so I decided to copy the newest definition with a new name (added sm as prefix) in my header file NtProcessInfo.h (included in the downloads).

    LONG ExitStatus;
    smPPEB PebBaseAddress;
    ULONG_PTR AffinityMask;
    LONG BasePriority;
    ULONG_PTR UniqueProcessId;
    ULONG_PTR InheritedFromUniqueProcessId;

Then, we get the basic information for a process via the NtQueryInformationProcess() function.

// Attempt to get basic info on process

NTSTATUS dwStatus = gNtQueryInformationProcess(hProcess,
// Did we successfully get basic info on process

if(dwStatus >= 0)
    // Basic Info

    spi.dwPID            = (DWORD)pbi->UniqueProcessId;
    spi.dwParentPID      = (DWORD)pbi->InheritedFromUniqueProcessId;
    spi.dwBasePriority   = (LONG)pbi->BasePriority;
    spi.dwExitStatus     = (NTSTATUS)pbi->ExitStatus;
    spi.dwPEBBaseAddress = (DWORD)pbi->PebBaseAddress;
    spi.dwAffinityMask   = (DWORD)pbi->AffinityMask;

Reading the PEB

From the basic information, we already get the base address, if any, of the PEB in the PebBaseAddress pointer variable. If the address is not equal to zero, we just pass this address to the ReadProcessMemory() function. If successful, it should return the process information in our PEB structure variable, which also contains the BeingDebugged and SessionId variables.

// Read Process Environment Block (PEB)

    if(ReadProcessMemory(hProcess, pbi->PebBaseAddress, &peb, sizeof(peb), &dwBytesRead))
        spi.dwSessionID    = (DWORD)peb.SessionId;
        spi.cBeingDebugged = (BYTE)peb.BeingDebugged;

The PEB structure is defined as:

typedef struct _smPEB {
    BYTE Reserved1[2];
    BYTE BeingDebugged;
    BYTE Reserved2[1];
    PVOID Reserved3[2];
    smPPEB_LDR_DATA Ldr;
    BYTE Reserved4[104];
    PVOID Reserved5[52];
    smPPS_POST_PROCESS_INIT_ROUTINE PostProcessInitRoutine;
    BYTE Reserved6[128];
    PVOID Reserved7[1];
    ULONG SessionId;
} smPEB, *smPPEB;

From this point, we also have the memory addresses for Ldr, which we are not using in this article. Basically, the PEB_LDR_DATA structure contains a doubly-linked list of the loaded modules in the process. We also have the memory address for ProcessParameters, which will give us the CommandLine...

// We got Process Parameters, is CommandLine filled in

if(peb_upp.CommandLine.Length > 0) {
    // Yes, try to read CommandLine

    pwszBuffer = (WCHAR *)HeapAlloc(hHeap,
    // If memory was allocated, continue

            // if commandline is larger than our variable, truncate

            if(peb_upp.CommandLine.Length >= sizeof(spi.szCmdLine)) 
                dwBufferSize = sizeof(spi.szCmdLine) - sizeof(TCHAR);
                dwBufferSize = peb_upp.CommandLine.Length;
            // Copy CommandLine to our structure variable

#if defined(UNICODE) || (_UNICODE)
            // Since core NT functions operate in Unicode

            // there is no conversion if application is

            // compiled for Unicode

            StringCbCopyN(spi.szCmdLine, sizeof(spi.szCmdLine),
                          pwszBuffer, dwBufferSize);
            // Since core NT functions operate in Unicode

            // we must convert to Ansi since our application

            // is not compiled for Unicode

            WideCharToMultiByte(CP_ACP, 0, pwszBuffer,
                                (int)(dwBufferSize / sizeof(WCHAR)),
                                spi.szCmdLine, sizeof(spi.szCmdLine),
                                NULL, NULL);
        if(!HeapFree(hHeap, 0, pwszBuffer)) {
            // failed to free memory

            bReturnStatus = FALSE;
            goto gnpiFreeMemFailed;
}    // Read CommandLine in Process Parameters

...and the ImagePathName variables as UNICODE_STRING structures. Unicode paths could be as long as 32K characters, and are usually prefixed with '\\?\' or '\??\'. Since native NT APIs operate in Unicode, we have to convert the buffers to ANSI when the calling application is not compiled for Unicode and is using TCHAR instead of WCHAR.

// We got Process Parameters, is ImagePathName filled in

if(peb_upp.ImagePathName.Length > 0) {
    // Yes, try to read Image Path

    pwszBuffer = (WCHAR *)HeapAlloc(hHeap,
    // If memory was allocated, continue

            // if image path is larger than our variable, truncate

            if(peb_upp.ImagePathName.Length >= sizeof(spi.szImgPath)) 
                dwBufferSize = sizeof(spi.szImgPath) - sizeof(TCHAR);
                dwBufferSize = peb_upp.ImagePathName.Length;
            // Copy ImagePathName to our structure variable

#if defined(UNICODE) || (_UNICODE)
            // Since core NT functions operate in Unicode

            // there is no conversion if application is

            // compiled for Unicode

            StringCbCopyN(spi.szImgPath, sizeof(spi.szImgPath),
                          pwszBuffer, dwBufferSize);
            // Since core NT functions operate in Unicode

            // we must convert to Ansi since our application

            // is not compiled for Unicode

            WideCharToMultiByte(CP_ACP, 0, pwszBuffer,
                                (int)(dwBufferSize / sizeof(WCHAR)),
                                spi.szImgPath, sizeof(spi.szImgPath),
                                NULL, NULL);
        if(!HeapFree(hHeap, 0, pwszBuffer)) {
            // failed to free memory

            bReturnStatus = FALSE;
            goto gnpiFreeMemFailed;
}    // Read ImagePathName in Process Parameters

For the system process (PID = 4 on XP and later, 8 on Win2K, and 2 on NT 4), we manually specify the path for the process since we know it is %SystemRoot%\System32\ntoskrnl.exe, but is not returned by the API. Ntoskrnl.exe could also be ntkrnlmp.exe if Symmetric Multi-Processing (SMP) is present, or ntkrnlpa.exe if Physical Address Extension (PAE) is present. In any case, the actual filename will be ntoskrnl.exe, but the OriginalFilename field in the file version block will contain the real name. We use the ExpandEnvironmentStrings() API to replace the %SystemRoot% system environment variable with the actual root path of Windows.

// System process for WinXP and later is PID 4 and we cannot access
// PEB, but we know it is aka ntoskrnl.exe so we will manually define it

if(spi.dwPID == 4)
                             spi.szImgPath, sizeof(spi.szImgPath));

As mentioned above with the PROCESS_BASIC_INFORMATION structure, the RTL_USER_PROCESS_PARAMETERS structure is defined in winternl.h and ntddk.h.

    BYTE Reserved1[16];
    PVOID Reserved2[10];
    UNICODE_STRING ImagePathName;
    UNICODE_STRING CommandLine;


Here, we free the NTDLL.DLL we loaded earlier. That's it!

void sm_FreeNTDLLFunctions(HMODULE hNtDll)
    gNtQueryInformationProcess = NULL;

Points of Interest

I wrote this article to share a method I learned while trying to get process information for a basic process explorer without using the simple Tool Help functions. Supposedly, the Tool Help functions started in Win9x, and was reluctantly incorporated into the NT based operating systems starting with XP. I wanted to dig in a little deeper and try using an NT Native API for my own experiences.

Some of the "safe" Windows API functions to obtain another process' information are:

  • ProcessIdToSessionId
  • CheckRemoteDebuggerPresent
  • GetExitCodeProcess
  • GetProcessAffinityMask
  • GetProcessImageFileName
  • CreateRemoteThread
  • Other Process and Thread Functions

Note: I did receive the following message during debug in the demo application, but appears to occur prior to WinMain, and appears to be handled since a second-chance exception is not thrown:

"First-chance exception at 0x7c918fea in GetNtProcessInfo.exe: 
              0xC0000005: Access violation writing location 0x00000010."

I did not get this exception with the real world implementation of NtProcessInfo.h and NtProcessInfo.cpp.


  • Initial release.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Steven A. Moore
United States United States
Steven Moore is a self-taught programmer on and off over the last 20+ years. He programmed in BASIC, Microsoft Visual Basic for Applications (VBA), Wang COBOL, a little Wang ASM, JavaScript, a little in C++ with inline ASM and Python 3.x. First article was GetNtProcessInfo on this site.

You may also be interested in...


Comments and Discussions

Questionself-taught programmer Pin
constm28-Jun-12 5:00
memberconstm28-Jun-12 5:00 
GeneralMy vote of 5 Pin
Pablo Aliskevicius18-Jun-12 1:27
memberPablo Aliskevicius18-Jun-12 1:27 
GeneralMy vote of 5 Pin
thomas.tsm12-Apr-12 23:22
memberthomas.tsm12-Apr-12 23:22 Getprocessimagefilename Pin
jlkdaslkfjd10-Jun-11 3:46
memberjlkdaslkfjd10-Jun-11 3:46 
Generalthank very much Pin
zinodream26-Mar-10 0:31
memberzinodream26-Mar-10 0:31 
GeneralThanks. Pin
DragonKeystone25-Jan-09 19:18
memberDragonKeystone25-Jan-09 19:18 
GeneralHandle Leak.. Pin
Chury7-Oct-08 22:21
memberChury7-Oct-08 22:21 
Generalcompile error Pin
gabrielmaldi2-Oct-08 18:20
membergabrielmaldi2-Oct-08 18:20 
QuestionThread state without ntdll or ResumeThread/SuspendThread Pin
open_mind_core27-Mar-08 9:39
memberopen_mind_core27-Mar-08 9:39 
QuestionNtQueryInformationProcess deprecated ? Pin
pg--az25-Jul-07 4:52
memberpg--az25-Jul-07 4:52 
AnswerRe: NtQueryInformationProcess deprecated ? Pin
Steven A. Moore25-Jul-07 18:52
memberSteven A. Moore25-Jul-07 18:52 
GeneralRe: NtQueryInformationProcess deprecated ? Pin
pg--az25-Jul-07 19:37
memberpg--az25-Jul-07 19:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190214.1 | Last Updated 21 Jul 2007
Article Copyright 2007 by Steven A. Moore
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid