Process handling in windows

Handle v4.22

By Mark Russinovich

Published: June 14, 2019

Download Handle (887 KB)

Introduction

Ever wondered which program has a particular file or directory open? Now you can find out. Handle is a utility that displays information about open handles for any process in the system. You can use it to see the programs that have a file open, or to see the object types and names of all the handles of a program.

You can also get a GUI-based version of this program, Process Explorer, here at Sysinternals.

Installation

You run Handle by typing «handle». You must have administrative privilege to run Handle.

Usage

Handle is targeted at searching for open file references, so if you do not specify any command-line parameters it will list the values of all the handles in the system that refer to open files and the names of the files. It also takes several parameters that modify this behavior.

usage: handle [[-a] [-u] | [-c [-l] [-y]] | [-s]] [-p

Parameter Description
-a Dump information about all types of handles, not just those that refer to files. Other types include ports, Registry keys, synchronization primitives, threads, and processes.
-c Closes the specified handle (interpreted as a hexadecimal number). You must specify the process by its PID.
WARNING: Closing handles can cause application or system instability.
-l Dump the sizes of pagefile-backed sections.
-y Don’t prompt for close handle confirmation.
-s Print count of each type of handle open.
-u Show the owning user name when searching for handles.
-p Instead of examining all the handles in the system, this parameter narrows Handle’s scan to those processes that begin with the name process. Thus:
handle -p exp
would dump the open files for all processes that start with «exp», which would include Explorer.
name This parameter is present so that you can direct Handle to search for references to an object with a particular name.
For example, if you wanted to know which process (if any) has «c:\windows\system32» open you could type:
handle windows\system
The name match is case-insensitive and the fragment specified can be anywhere in the paths you are interested in.

Handle Output

When not in search mode (enabled by specifying a name fragment as a parameter), Handle divides its output into sections for each process it is printing handle information for. Dashed lines are used as a separator, immediately below which you will see the process name and its process id (PID). Beneath the process name are listed handle values (in hexadecimal), the type of object the handle is associated with, and the name of the object if it has one.

When in search mode, Handle prints the process names and id’s are listed on the left side and the names of the objects that had a match are on the right.

More Information

You can find more information on the Object Manager in Windows Internals, 4th Edition or by browsing the Object Manager name-space with WinObj.

Download Handle (887 KB)

Process. Handle Свойство

Определение

Получает собственный дескриптор связанного процесса. Gets the native handle of the associated process.

Значение свойства

Дескриптор, присвоенный процессу операционной системой при запуске. The handle that the operating system assigned to the associated process when the process was started. Система использует этот дескриптор для хранения атрибутов процесса. The system uses this handle to keep track of process attributes.

Исключения

Процесс не был запущен или был завершен. The process has not been started or has exited. Невозможно прочитать свойство Handle, поскольку ни один процесс не связан с этим экземпляром Process. The Handle property cannot be read because there is no process associated with this Process instance.

-или- -or- Экземпляр Process был присоединен к запущенному процессу, но у вас нет необходимых разрешений для получения маркера с полными правами доступа. The Process instance has been attached to a running process but you do not have the necessary permissions to get a handle with full access rights.

Вы пытаетесь получить доступ к свойству Handle процесса, запущенного на удаленном компьютере. You are trying to access the Handle property for a process that is running on a remote computer. Это свойство доступно только для процессов, запущенных на локальном компьютере. This property is available only for processes that are running on the local computer.

Комментарии

Приложение может получить обработчик для процесса, который можно использовать в качестве параметра для многих функций обработки и управления данными. An application can obtain a handle to a process that can be used as a parameter to many process-information and control functions. Этот обработчик можно использовать для инициализации WaitHandle или для вызова собственных методов с помощью вызова неуправляемого кода. You can use this handle to initialize a WaitHandle or to call native methods with platform invoke.

Этот дескриптор процесса является частным для приложения, иными словами, дескрипторы процессов не могут быть общими. This process handle is private to an application—in other words, process handles cannot be shared. Процесс также имеет процесс Id , который, в отличие от Handle , является уникальным и, следовательно, действителен во всей системе. A process also has a process Id which, unlike the Handle, is unique and, therefore, valid throughout the system.

Только процессы, запущенные через вызов, Start устанавливают Handle свойство соответствующих Process экземпляров. Only processes started through a call to Start set the Handle property of the corresponding Process instances.

Handling end process of a windows app

Is it possible to capture the task manager end process of a windows application within the same windows application itself? I am using a C# 2.0 win app and I would like to do some database processing (change a flag from ‘Y’ to ‘N’ in the DB) when an end process happens.

6 Answers 6

No, it is not possible to hook the operating system’s decision to end a process. Note, this is not done by task manger, ending a process is the responsibility of the kernel.

You will need to do two things here:

  1. Connect event handlers to the normal user interface messages that tell a application to exit. Use these events to persist data, free resources, and otherwise exit cleanly.
  2. Handle exceptions as appropriate to catch errors and clean up and save data if possible.

Here are a three links to Raymond’s blog explaining why you cannot do what you are asking.

Also, I addressed a similar StackOverflow question here.

How about a slightly different approach:

Have your application update a date time field e.g. LastPollDate every so often while it is running, and have a separate field e.g. «AppTerminatedNormally» which you set to N, and change to Y if you get a form close event.

If the app is killed via Task Manager, the date will not be updated any more, and your AppTerminatedNormally will still be no.

This way you could run a query that finds all rows where LastPollDate is older than 10 minutes and AppTerminatedNormally is N, and you would have all the sessions that were abnormally terminated.

You’re all gonna spit at this post, but here goes.

You’re trying to solve the problem at the wrong level (i.e. running code in your app when the kernal is killing the app). The real problem is about ensuring that the database correctly reflect the presence (or absence) of it’s client application/s.

To solve this, avoid allowing applications to be in an «incongruent state» between user interactions. In other words, don’t start transactions that you can’t commit quickly, don’t write data to files that leaves the file in a half-written or unreadable state, and don’t hold resources in external to your application an incongruent state outside of user interactions. Put differently, if your app isn’t busy responding to an event handler, it should be ready to close immediately.

If you follow the above practise, you’ll find very few scenarios where you need to «quickly clean up» before terminating. Outside of interactions where a user clicks «OK» or «Save», etc. a well written application should be able to survive immediate termination without any lasting damage or corruption of it’s data stores.

If you absolutely have to set a flag in the database upon exit (which sounds typical of a pattern used to detect whether a user is logged in or not), then consider either of the following alternatives:

Periodically (perhaps once every 30 seconds) insert/update a timestamp-like field in the database, to indicate how recently an application was online. Other applications can inspect these timestamps to determine how recently another application was online. if the value is within the last 30 seconds, the other app is still opnline.

As Woodhenge rightly suggested, create a seperate process (ideally a service) to monitor the status of the main application. Windows services can be configured to automatically restart in the event of a failure of the service. This monitoring process will then issue timestamps to the database.

Notice that both of the above suggestions solve the real problem (detecting whether applications are accessing the database) without ever leaving the database in an «incongruent state» (the aforementioned flag is «Y» when the application is actualy dead and the flag should be «N»).

Process. Main Window Handle Свойство

Определение

Получает дескриптор главного окна связанного процесса. Gets the window handle of the main window of the associated process.

Значение свойства

Созданный системой дескриптор главного окна связанного процесса. The system-generated window handle of the main window of the associated process.

Исключения

Свойство MainWindowHandle не определено, так как процесс завершился. The MainWindowHandle is not defined because the process has exited.

Вы пытаетесь получить доступ к свойству MainWindowHandle процесса, запущенного на удаленном компьютере. You are trying to access the MainWindowHandle property for a process that is running on a remote computer. Это свойство доступно только для процессов, запущенных на локальном компьютере. This property is available only for processes that are running on the local computer.

Комментарии

Главное окно — это окно, открытое процессом, который в данный момент имеет фокус ( TopLevel форма). The main window is the window opened by the process that currently has the focus (the TopLevel form). Необходимо использовать метод, Refresh чтобы обновить объект, Process чтобы получить наиболее актуальный обработчик основного окна, если он был изменен. You must use the Refresh method to refresh the Process object to get the most up to date main window handle if it has changed. В общем случае, поскольку обработчик окна кэшируется, сначала следует использовать, Refresh чтобы получить текущий маркер. In general, because the window handle is cached, use Refresh beforehand to guarantee that you’ll retrieve the current handle.

Свойство можно получить MainWindowHandle только для процессов, запущенных на локальном компьютере. You can get the MainWindowHandle property only for processes that are running on the local computer. MainWindowHandleСвойство — это значение, уникально идентифицирующее окно, связанное с процессом. The MainWindowHandle property is a value that uniquely identifies the window that is associated with the process.

С процессом связано главное окно, только если процесс имеет графический интерфейс. A process has a main window associated with it only if the process has a graphical interface. Если связанный процесс не имеет главного окна, MainWindowHandle это значение равно нулю. If the associated process does not have a main window, the MainWindowHandle value is zero. Значение также равно нулю для процессов, которые были скрыты, то есть процессов, которые не отображаются на панели задач. The value is also zero for processes that have been hidden, that is, processes that are not visible in the taskbar. Это может быть так для процессов, которые отображаются в виде значков в области уведомлений в правом углу панели задач. This can be the case for processes that appear as icons in the notification area, at the far right of the taskbar.

Если вы только что начали процесс и хотите использовать его основной обработчик окна, рассмотрите возможность использования WaitForInputIdle метода для завершения процесса запуска, гарантируя создание обработчика основного окна. If you have just started a process and want to use its main window handle, consider using the WaitForInputIdle method to allow the process to finish starting, ensuring that the main window handle has been created. В противном случае будет создаваться исключение. Otherwise, an exception will be thrown.

Console Handles

A console process uses handles to access the input and screen buffers of its console. A process can use the GetStdHandle, CreateFile, or CreateConsoleScreenBuffer function to open one of these handles.

The GetStdHandle function provides a mechanism for retrieving the standard input ( STDIN ), standard output ( STDOUT ), and standard error ( STDERR ) handles associated with a process. During console creation, the system creates these handles. Initially, STDIN is a handle to the console’s input buffer, and STDOUT and STDERR are handles of the console’s active screen buffer. However, the SetStdHandle function can redirect the standard handles by changing the handle associated with STDIN , STDOUT , or STDERR . Because the parent’s standard handles are inherited by any child process, subsequent calls to GetStdHandle return the redirected handle. A handle returned by GetStdHandle may, therefore, refer to something other than console I/O. For example, before creating a child process, a parent process can use SetStdHandle to set a pipe handle to be the STDIN handle that is inherited by the child process. When the child process calls GetStdHandle, it gets the pipe handle. This means that the parent process can control the standard handles of the child process. The handles returned by GetStdHandle have GENERIC_READ | GENERIC_WRITE access unless SetStdHandle has been used to set the standard handle to have lesser access.

The value of the handles returned by GetStdHandle are not 0, 1, and 2, so the standard predefined stream constants in Stdio.h ( STDIN , STDOUT , and STDERR ) cannot be used in functions that require a console handle.

The CreateFile function enables a process to get a handle to its console’s input buffer and active screen buffer, even if STDIN and STDOUT have been redirected. To open a handle to a console’s input buffer, specify the CONIN$ value in a call to CreateFile. Specify the CONOUT$ value in a call to CreateFile to open a handle to a console’s active screen buffer. CreateFile enables you to specify the read/write access of the handle that it returns.

The CreateConsoleScreenBuffer function creates a new screen buffer and returns a handle. This handle can be used in any function that accepts a handle to console output. The new screen buffer is not active (displayed) until its handle is specified in a call to the SetConsoleActiveScreenBuffer function. Note that changing the active screen buffer does not affect the handle returned by GetStdHandle. Similarly, using SetStdHandle to change the STDOUT handle does not affect the active screen buffer.

Console handles returned by CreateFile and CreateConsoleScreenBuffer can be used in any of the console functions that require a handle to a console’s input buffer or of a console screen buffer. Handles returned by GetStdHandle can be used by the console functions if they have not been redirected to refer to something other than console I/O. If a standard handle has been redirected to refer to a file or a pipe, however, the handle can only be used by the ReadFile and WriteFile functions. GetFileType can assist in determining what device type the handle refers to. A console handle presents as FILE_TYPE_CHAR .

A process can use the DuplicateHandle function to create a duplicate console handle that has different access or inheritability from the original handle. Note, however, that a process can create a duplicate console handle only for its own use. This differs from other handle types (such as file, pipe, or mutex objects), for which DuplicateHandle can create a duplicate that is valid for a different process. Access to a console must be shared during creation of the other process or may be requested by the other process through the AttachConsole mechanism.

To close a console handle, a process can use the CloseHandle function.

Читайте также:  Количество портов поддерживаемых windows
Оцените статью