Windows current process name

Finding the process ID

Each process running in Windows is assigned a unique decimal number called the process ID (PID). This number is used in a number of ways, for example to specify the process when attaching a debugger to it.

This topic describes how you can determine the PID for a given app using Task Manager, the tasklist Windows command, the TList utility, or the debugger.

Task Manager

Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager.

In Windows 10, first click More details to expand the information displayed. From the Processes tab, select the Details tab to see the process ID listed in the PID column.

Click on any column name to sort. You can right click a process name to see more options for a process.

Some kernel errors may cause delays in Task Manager’s graphical interface.

The tasklist command

Use the built in Windows tasklist command from a command prompt to display all processes, their PIDs, and a variety of other details.

Use tasklist /? to display command line help.

TList utility

Task List Viewer (TList), or tlist.exe, is a command-line utility that displays the list of tasks, or user-mode processes, currently running on the local computer. TList is included in the Debugging Tools for Windows. For information on how to download and install the debugging tools, see Download Debugging Tools for Windows.

If you installed the Windows Driver Kit in the default directory on a 64 bit PC, the debugging tools are located here:

C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\

When you run TList from the command prompt, it will display a list of all the user-mode processes in memory with a unique PID number. For each process, it shows the PID, process name, and, if the process has a window, the title of that window.

For more information, see TList.

The .tlist debugger command

If there’s already a user-mode debugger running on the system in question, the .tlist (List Process IDs) command will display a list of all PIDs on that system.

PowerShell Get-Process command

To work with automation scripts, use the Get-Process PowerShell command. Specify a specific process name, to see the process ID for that process.

For more information, see Get-Process.

CSRSS and user-mode drivers

To debug a user-mode driver running on another computer, debug the Client Server Run-Time Subsystem (CSRSS) process. For more information, see Debugging CSRSS.

GetProcessImageFileNameA function (psapi.h)

Retrieves the name of the executable file for the specified process.

Syntax

Parameters

A handle to the process. The handle must have the PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access right. For more information, see Process Security and Access Rights.

Windows ServerВ 2003 and WindowsВ XP:В В The handle must have the PROCESS_QUERY_INFORMATION access right.

A pointer to a buffer that receives the full path to the executable file.

The size of the lpImageFileName buffer, in characters.

Return value

If the function succeeds, the return value specifies the length of the string copied to the buffer.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The file Psapi.dll is installed in the %windir%\System32 directory. If there is another copy of this DLL on your computer, it can lead to the following error when running applications on your system: «The procedure entry point GetProcessImageFileName could not be located in the dynamic link library PSAPI.DLL.» To work around this problem, locate any versions that are not in the %windir%\System32 directory and delete or rename them, then restart.

The GetProcessImageFileName function returns the path in device form, rather than drive letters. For example, the file name C:\Windows\System32\Ctype.nls would look as follows in device form:

To retrieve the module name of the current process, use the GetModuleFileName function with a NULL module handle. This is more efficient than calling the GetProcessImageFileName function with a handle to the current process.

To retrieve the name of the main executable module for a remote process in win32 path format, use the QueryFullProcessImageName function.

Starting with WindowsВ 7 and Windows ServerВ 2008В R2, Psapi.h establishes version numbers for the PSAPI functions. The PSAPI version number affects the name used to call the function and the library that a program must load.

If PSAPI_VERSION is 2 or greater, this function is defined as K32GetProcessImageFileName in Psapi.h and exported in Kernel32.lib and Kernel32.dll. If PSAPI_VERSION is 1, this function is defined as GetProcessImageFileName in Psapi.h and exported in Psapi.lib and Psapi.dll as a wrapper that calls K32GetProcessImageFileName.

Читайте также:  Где искать драйвера для windows 10

Programs that must run on earlier versions of Windows as well as WindowsВ 7 and later versions should always call this function as GetProcessImageFileName. To ensure correct resolution of symbols, add Psapi.lib to the TARGETLIBS macro and compile the program with -DPSAPI_VERSION=1. To use run-time dynamic linking, load Psapi.dll.

The psapi.h header defines GetProcessImageFileName as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.

!process

The !process extension displays information about the specified process, or about all processes, including the EPROCESS block.

This extension can be used only during kernel-mode debugging.

Parameters

/s **** Session
Specifies the session that owns the desired process.

/m **** Module
Specifies the module that owns the desired process.

Process
Specifies the hexadecimal address or the process ID of the process on the target computer.

The value of Process determines whether the !process extension displays a process address or a process ID . If Process is omitted in any version of Windows, the debugger displays data only about the current system process. If Process is 0 and ImageName is omitted, the debugger displays information about all active processes. If -1 is specified for Process information about the current process is displayed.

Flags
Specifies the level of detail to display. Flags can be any combination of the following bits. If Flags is 0, only a minimal amount of information is displayed. The default varies according to the version of Windows and the value of Process. The default is 0x3 if Process is omitted or if Process is either 0 or -1; otherwise, the default is 0xF.

Bit 0 (0x1)
Displays time and priority statistics.

Bit 1 (0x2)
Displays a list of threads and events associated with the process, and their wait states.

Bit 2 (0x4)
Displays a list of threads associated with the process. If this is included without Bit 1 (0x2), each thread is displayed on a single line. If this is included along with Bit 1, each thread is displayed with a stack trace.

Bit 3 (0x8)
Displays the return address and the stack pointer for each function The display of function arguments is suppressed.

Bit 4 (0x10)
Sets the process context equal to the specified process for the duration of this command. This results in a more accurate display of thread stacks. Because this flag is equivalent to using .process /p /r for the specified process, any existing user-mode module list will be discarded. If Process is zero, the debugger displays all processes, and the process context is changed for each one. If you are only displaying a single process and its user-mode state has already been refreshed (for example, with .process /p /r), it is not necessary to use this flag. This flag is only effective when used with Bit 0 (0x1).

ImageName
Specifies the name of the process to be displayed. The debugger displays all processes whose executable image names match ImageName. The image name must match that in the EPROCESS block. In general, this is the executable name that was invoked to start the process, including the file extension (usually .exe), and truncated after the fifteenth character. There is no way to specify an image name that contains a space. When ImageName is specified, Process must be zero.

Additional Information

For information about processes in kernel mode, see Changing Contexts. For more information about analyzing processes and threads, see Microsoft Windows Internals, by Mark Russinovich and David Solomon.

Remarks

The following is an example of a !process 0 0 display:

The following table describes some of the elements of the !process 0 0 output.

The eight-character hexadecimal number after the word PROCESS is the address of the EPROCESS block. In the final entry in the preceding example, the process address is 0x809258E0.

The hexadecimal number after the word Cid. In the final entry in the preceding example, the PID is 0x44, or decimal 68.

Process Environment Block (PEB)

The hexadecimal number after the word Peb is the address of the process environment block. In the final entry in the preceding example, the PEB is located at address 0x7FFDE000.

Parent process PID

The hexadecimal number after the word ParentCid is the PID of the parent process. In the final entry in the preceding example, the parent process PID is 0x26, or decimal 38.

The name of the module that owns the process. In the final entry in the preceding example, the owner is spoolss.exe. In the first entry, the owner is the operating system itself.

Process object address

The hexadecimal number after the word ObjectTable. In the final entry in the preceding example, the address of the process object is 0x80925c68.

To display full details on one process, set Flags to 7. The process itself can be specified by setting Process equal to the process address, setting Process equal to the process ID, or setting ImageName equal to the executable image name. Here is an example:

Note that the address of the process object can be used as input to other extensions, such as !handle, to obtain further information.

The following table describes some of the elements in the previous example.

Element Meaning

Lists the amount of time that has elapsed since the process was created. This is displayed in units of Hours:Minutes:Seconds.Milliseconds.

Lists the amount of time the process has been running in user mode. If the value for UserTime is exceptionally high, it might identify a process that is depleting system resources. Units are the same as those of ElapsedTime.

Lists the amount of time the process has been running in kernel mode. If the value for KernelTime is exceptionally high, it might identify a process that is depleting system resources. Units are the same as those of ElapsedTime.

Working Set sizes

Lists the current, minimum and maximum working set size for the process, in pages. An exceptionally large working set size can be a sign of a process that is leaking memory or depleting system resources.

Lists the paged and nonpaged pool used by the process. On a system with a memory leak, looking for excessive nonpaged pool usage on all the processes can tell you which process has the memory leak.

Indicates whether or not the process was created by the POSIX or Interix subsystems.

Indicates the number of private (non-sharable) pages currently being used by the process. This includes both paged in and paged out memory.

In addition to the process list information, the thread information contains a list of the resources on which the thread has locks. This information is listed in the third line of output after the thread header. In this example, the thread has a lock on one resource, a SynchronizationEvent with an address of 80144fc0. By comparing this address to the list of locks shown by the !kdext*.locks extension, you can determine which threads have exclusive locks on resources.

The !stacks extension gives a brief summary of the state of every thread. This can be used instead of the !process extension to get a quick overview of the system, especially when debugging multithread issues, such as resource conflicts or deadlocks.

Класс Win32_Process — работа с процессами

Класс Win32_Process служит для работы с процессами Windows. С его помощью можно получить обширный список параметров заданного процесса или целой группы. А также получить имя учетной записи и ее идентификатор, создать новый процесс, завершить заданный, изменить приоритет и многое другое.

Сначала я приведу вам описание класса Win32_Process, а потом покажу примеры с его использованием.

Свойства класса Win32_Process

Caption – Содержит описание процесса (короткая форма).

CommandLine – Содержит полный путь к приложению (если оно существует), которое отвечает за запуск процесса.

CreationClassName – имя класса, который создал процесс, как правило – Win32_Process

CreationDate – хранит в себе значение в формате дата, собственно время начала запуска процесса

CSCreationClassName – как и свойство CreationClassName выводит имя класса.

CSName – данное свойство позволяет получить имя компьютера, на котором запущен процесс.

Description — Содержит описание процесса (полная форма).

ExecutablePath – фактически, как и свойство CommandLine , хранит полный путь к исполняемому файлу процесса.

ExecutionState – это свойство не нашло реализации и всегда возвращает пустое значение ( null )

Handle – описатель процесса, фактически содержит такое же значение, как и свойство ProcessID

HandleCount – количественное значение дескрипторов, которые открыты в данный момент текущим процессом.

InstallDate – дата создания объекта, объект может быть создан и без записи значения в это свойство, тогда свойство вернет null

KernelModeTime – время работы в режиме ядра

UserModeTime – время работы в пользовательском режиме, данные свойства, как и KernelModeTime позволяют определить загрузку процессора заданным процессом.

MaximumWorkingSetSize — Максимально возможный размер рабочего набора процесса (рабочий набор процесса — это набор страниц, доступных процессу в физической оперативной памяти)

MinimumWorkingSetSize — Минимально возможный размер рабочего набора процесса

Name – свойство хранит имя процесса и как правило, совпадает со значением свойства Caption .

OSCreationClassName – вернет имя класса.

OSName – содержит имя ОС

OtherOperationCount — Число выполненных операций ввода/вывода, отличных от операции чтения или записи

OtherTransferCount — Размер данных, переданных в процессе выполнения операций, отличных от операции чтения или записи.

PageFaults – количество ошибок, которые возникают при обращении к блоку памяти.

PageFileUsage – определяет размер в байтах части файла подкачки, что используется на данный момент процессом.

ParentProcessID – свойство позволяет получить идентификатор родительского процесса (того, что создал текущий процесс).

PeakPageFileUsage – хранит информацию в байтах части файла подкачки, что использовалась на протяжении работы всего процесса.

PeakVirtualSize — Максимальное значение размера виртуального адресного пространства, что использовалось процессом единовременно.

PeakWorkingSetSize — Максимальное значение размера рабочего набора процесса за все время работы

Priority – данное свойство позволяет узнать приоритет процесса, оно может принимать значение от 0 (минимум) до 31(максимум).

ProcessID – собственно, идентификатор процесса, в большинстве случаев, именно данный параметр служит для определения процесса, так как является всегда уникальным из целого списка.

ReadOperationCount — количество выполненных процессом операций чтения

ReadTransferCount — размер прочитанных данных

ThreadCount — количество активных потоков в процессе

VirtualSize — Текущий размер виртуального адресного пространства в байтах, используемого процессом

WindowsVersion – версия сборки ОС.

WorkingSetSize — Размер памяти в байтах, который нужно для успешного выполнения процесса в ОС, которая использует страничную организацию памяти

WriteOperationCount – количество выполненных процессом операций записи

WriteTransferCount — Размер записанных данных

Методы класса Win32_Process

AttachDebugger() – позволяет запустить отладчик, который установлен в система по умолчанию для отладки системы.

Create(CommandLine, CurrentDirectory, ProcessStartupInformation, ProcessId) – данный метод позволяет создать новый процесс. Метод вернет значение 0 (при успехе) или код ошибки. Как видим методу передаются 4 параметры, первые три являются входящими, а четвертый ( ProcessId ) – будет хранить идентификатор процесса, присвоенный системой.

CommandLine – путь к файлу, который породит процесс

CurrentDirectory – рабочий каталог, который, используемый созданным процессом, при отсутствии данного параметра, будет приниматься значение из параметра CommandLine .

ProcessStartupInformation — начальная конфигурация процесса (объект класса Win32_ProcessStartup ), при отсутствии параметра будет приниматься пустая строка ( \»\» ).

GetOwner(User, Domain) – данный метод полезен тем, что позволяет получить имя пользователя (User) создавшего процесс и имя домена в котором запущен текущий процесс ( Domain ). Стоит обратить внимание, что не важно, какие имена переменных передаются методу. Схема вызова метода GetOwner для языка vbscript и jscript разная, как это происходит мы рассмотрим ниже.

GetOwnerSid(Sid) – метод принимает всего один параметр, в котором будет храниться идентификатор безопасности ( Security IDentifier, SID ) владельца процесса

SetPriority(Priority) – метод позволяет задать приоритет процесса. Параметр Priority принимает следующие значения: 64 (низкий), 16 384 (ниже среднего), 32 (средний), 32 768 (выше среднего), 128 (высокий), 256 (процесс будет выполняться в реальном времени – может подвесить систему)

Terminate(Reason) – позволяет принудительно завершить текущий процесс и все дочерние. Метод, как и все остальные, вернет ноль при успехе или код ошибки при неудачи. Параметр позволяет задать код выхода.

Хорошо, теорию прошли, теперь можно и попрактиковаться.

Получаем имя процесса, SID и имя домена/пользователя (класс Win32_Process, язык JScript)

Сперва происходит подключение к пространству имен WMI CIMv2 с помощью функции GetObject , результат будет храниться в переменной objWMI . Видим, что для экранизации косой черты, мы ее прописываем дважды. Далее нам нужно обработать коллекцию, которая возвращается после вызова класса Win32_Process. В языке jscript для обработки коллекции служит встроенный объект Enumerator (смотри статью “Урок 17 по JScript: Enumerator — объект для работы с коллекциями”). Далее идет использования цикла for для перебора всех элементов коллекции. В цикле мы вызываем функцию GetOwner (она вернет значение в переменную output, которая хранит код выхода и через которую мы получаем имя домена и пользователя) и GetOwnerSid (она вернет значение в переменную output_SID, которая хранит код выхода и через которую мы получаем значение SID) через метод ExecMethod_ . Я не делал проверки, то есть, если переменные output или output_SID возвращают ноль, значит, запрос прошел удачно, иначе, мы получим пустое значение null. Весь список записывается в переменную list . Далее происходит вызов функции ShowInNotepad , в которой данные записываются во временный файл, и который потом открывается с помощью программы wordpad.exe.

Получаем имя процесса, SID и имя домена/пользователя (класс Win32_Process, язык JScript)

Тут стоит обратить внимание на следующую особенность: Вызов методов GetOwner и GetOwnerSid происходит через переменную objItem а не через функцию ExecMethod_ как в примере на jscript. Также видим, что переменные strSID, strDomain и strUser мы указали как параметры, то есть, мы могли указать и другие названия переменных.

Спасибо за внимание. Автор блога Владимир Баталий

Оцените статью
Element Meaning
WAIT The parenthetical comment after this heading gives the reason for the wait. The command dt nt!_KWAIT_REASON will display a list of all wait reasons.