- Process. Id Свойство
- Определение
- Значение свойства
- Исключения
- Примеры
- Комментарии
- Process ID Limits And Reservations
- Node PID limits
- Pod PID limits
- PID based eviction
- What’s next
- Feedback
- Что такое «System Idle Process» и почему он использует так много ресурсов процессора?
- Что такое System Idle Process
- Зачем Windows нужен процесс простоя системы?
- Почему он использует так много процессора?
- Но мой компьютер медленный!
- Process Handles and Identifiers
- How to get process id by its service name with a script to variable
- 6 Answers 6
Process. Id Свойство
Определение
Получает уникальный идентификатор связанного процесса. Gets the unique identifier for the associated process.
Значение свойства
Созданный системой уникальный идентификатор, на который ссылается этот экземпляр Process. The system-generated unique identifier of the process that is referenced by this Process instance.
Исключения
Свойство Id процесса не задано. The process’s Id property has not been set.
-или- -or- С этим объектом Process не связаны никакие процессы. There is no process associated with this Process object.
Примеры
В следующем примере показано, как получить объект Id для всех работающих экземпляров приложения. The following example demonstrates how to obtain the Id for all running instances of an application. Код создает новый экземпляр блокнота, перечисляет все экземпляры Блокнота, а затем позволяет пользователю ввести Id номер, чтобы удалить конкретный экземпляр. The code creates a new instance of Notepad, lists all the instances of Notepad, and then allows the user to enter the Id number to remove a specific instance.
Комментарии
Этот процесс Id недействителен, если связанный процесс не выполняется. The process Id is not valid if the associated process is not running. Поэтому перед попыткой получить свойство необходимо убедиться в том, что процесс выполняется Id . Therefore, you should ensure that the process is running before attempting to retrieve the Id property. До завершения процесса идентификатор процесса однозначно определяет процесс во всей системе. Until the process terminates, the process identifier uniquely identifies the process throughout the system.
Процесс, работающий на локальном или удаленном компьютере, можно подключить к новому Process экземпляру, передав идентификатор процесса в GetProcessById метод. You can connect a process that is running on a local or remote computer to a new Process instance by passing the process identifier to the GetProcessById method. GetProcessById — Это static метод, который создает новый компонент и устанавливает Id свойство для нового Process экземпляра автоматически. GetProcessById is a static method that creates a new component and sets the Id property for the new Process instance automatically.
Идентификаторы процессов могут повторно использоваться системой. Process identifiers can be reused by the system. IdЗначение свойства является уникальным только во время выполнения связанного процесса. The Id property value is unique only while the associated process is running. После завершения процесса система может повторно использовать Id значение свойства для несвязанного процесса. After the process has terminated, the system can reuse the Id property value for an unrelated process.
Поскольку идентификатор уникален в системе, его можно передать другим потокам в качестве альтернативы передаче Process экземпляра. Because the identifier is unique on the system, you can pass it to other threads as an alternative to passing a Process instance. Это действие может сэкономить системные ресурсы, тем самым гарантируя правильную идентификацию процесса. This action can save system resources yet guarantee that the process is correctly identified.
Process ID Limits And Reservations
Kubernetes allow you to limit the number of process IDs (PIDs) that a Pod can use. You can also reserve a number of allocatable PIDs for each node for use by the operating system and daemons (rather than by Pods).
Process IDs (PIDs) are a fundamental resource on nodes. It is trivial to hit the task limit without hitting any other resource limits, which can then cause instability to a host machine.
Cluster administrators require mechanisms to ensure that Pods running in the cluster cannot induce PID exhaustion that prevents host daemons (such as the kubelet or kube-proxy, and potentially also the container runtime) from running. In addition, it is important to ensure that PIDs are limited among Pods in order to ensure they have limited impact on other workloads on the same node.
You can configure a kubelet to limit the number of PIDs a given Pod can consume. For example, if your node’s host OS is set to use a maximum of 262144 PIDs and expect to host less than 250 Pods, one can give each Pod a budget of 1000 PIDs to prevent using up that node’s overall number of available PIDs. If the admin wants to overcommit PIDs similar to CPU or memory, they may do so as well with some additional risks. Either way, a single Pod will not be able to bring the whole machine down. This kind of resource limiting helps to prevent simple fork bombs from affecting operation of an entire cluster.
Per-Pod PID limiting allows administrators to protect one Pod from another, but does not ensure that all Pods scheduled onto that host are unable to impact the node overall. Per-Pod limiting also does not protect the node agents themselves from PID exhaustion.
You can also reserve an amount of PIDs for node overhead, separate from the allocation to Pods. This is similar to how you can reserve CPU, memory, or other resources for use by the operating system and other facilities outside of Pods and their containers.
PID limiting is a an important sibling to compute resource requests and limits. However, you specify it in a different way: rather than defining a Pod’s resource limit in the .spec for a Pod, you configure the limit as a setting on the kubelet. Pod-defined PID limits are not currently supported.
Node PID limits
Kubernetes allows you to reserve a number of process IDs for the system use. To configure the reservation, use the parameter pid= in the —system-reserved and —kube-reserved command line options to the kubelet. The value you specified declares that the specified number of process IDs will be reserved for the system as a whole and for Kubernetes system daemons respectively.
Pod PID limits
Kubernetes allows you to limit the number of processes running in a Pod. You specify this limit at the node level, rather than configuring it as a resource limit for a particular Pod. Each Node can have a different PID limit.
To configure the limit, you can specify the command line parameter —pod-max-pids to the kubelet, or set PodPidsLimit in the kubelet configuration file.
PID based eviction
You can configure kubelet to start terminating a Pod when it is misbehaving and consuming abnormal amount of resources. This feature is called eviction. You can Configure Out of Resource Handling for various eviction signals. Use pid.available eviction signal to configure the threshold for number of PIDs used by Pod. You can set soft and hard eviction policies. However, even with the hard eviction policy, if the number of PIDs growing very fast, node can still get into unstable state by hitting the node PIDs limit. Eviction signal value is calculated periodically and does NOT enforce the limit.
PID limiting — per Pod and per Node sets the hard limit. Once the limit is hit, workload will start experiencing failures when trying to get a new PID. It may or may not lead to rescheduling of a Pod, depending on how workload reacts on these failures and how liveleness and readiness probes are configured for the Pod. However, if limits were set correctly, you can guarantee that other Pods workload and system processes will not run out of PIDs when one Pod is misbehaving.
What’s next
- Refer to the PID Limiting enhancement document for more information.
- For historical context, read Process ID Limiting for Stability Improvements in Kubernetes 1.14.
- Read Managing Resources for Containers.
- Learn how to Configure Out of Resource Handling.
Feedback
Was this page helpful?
Thanks for the feedback. If you have a specific, answerable question about how to use Kubernetes, ask it on Stack Overflow. Open an issue in the GitHub repo if you want to report a problem or suggest an improvement.
Что такое «System Idle Process» и почему он использует так много ресурсов процессора?
Вы когда-нибудь открывали диспетчер задач и замечали, что System Idle Process использует 90% или более вашего процессора? Это неплохо. Вот что на самом деле делает этот процесс.
Что такое System Idle Process
Если вы когда-нибудь ковырялись в диспетчере задач — пользователям Windows 10 нужно заглянуть на вкладку «Сведения» — вы увидите, что процесс простоя системы использует большую часть, если не все, вашего ЦП. Но процесс простоя системы — только это; процесс холостого хода, сделанный операционной системой. Без этого процесса, постоянно занятого вашим процессором, ваша система потенциально может зависнуть.
Другими словами, ресурсы ЦП, используемые Системным процессом простоя, являются просто ресурсами ЦП, которые не используются. Если программы используют 5% вашего ЦП, процесс простоя системы будет использовать 95% вашего ЦП. Вы можете думать об этом как о простом заполнителе. Вот почему диспетчер задач описывает этот процесс как «процент времени, в течение которого процессор простаивает». У него PID (идентификатор процесса) 0.
Windows скрывает информацию о процессе простоя системы на обычной вкладке «Процессы» в диспетчере задач Windows 10, чтобы упростить задачу, но она по-прежнему отображается на вкладке «Сведения».
Зачем Windows нужен процесс простоя системы?
Без этого процесса, постоянно занятого вашим процессором, ваша система может потенциально зависнуть. Windows запускает этот процесс как часть учетной записи пользователя SYSTEM, поэтому он всегда активен в фоновом режиме, пока работает Windows.
Процессы простоя системы являются родными для операционных систем Windows NT, начиная с 1993 года — они также появляются в Unix-подобных операционных системах, таких как Linux, но работают немного по-другому. Процесс простоя системы — это обычная часть вашей ОС, в которой выполняется многопроцессорная система с одним потоком на каждом ядре ЦП, в то время как системы, использующие гиперпоточность, имеют один поток простоя на логический процессор.
Единственная цель System Idle Process — держать процессор занятым чем-то — буквально чем-нибудь — пока он ожидает следующего вычисления или процесса, поданного в него. Причина, по которой все это работает, заключается в том, что незанятые потоки используют нулевой приоритет, который ниже, чем у обычных потоков, что позволяет им выталкиваться из очереди, когда в ОС есть допустимые процессы, которые должны быть запущены. Затем, как только процессор завершает эту работу, он готов снова обрабатывать процесс простоя системы. Если незанятые потоки всегда находятся в состоянии готовности, если они еще не запущены, центральный процессор работает и ожидает чего-либо, что ОС ему выдаст.
Почему он использует так много процессора?
Как уже упоминалось ранее, этот процесс использует много ресурсов ЦП, и это то, что вы заметите, если откроете диспетчер задач в поисках ресурсоемких процессов. Это нормально, потому что это специальная задача, запускаемая планировщиком ОС только тогда, когда ваш процессор простаивает, что, если вы не делаете что-то, требующее большой вычислительной мощности, будет выглядеть довольно высоким.
Чтобы понять число рядом с процессом в диспетчере задач, вы должны думать, что это означает противоположное тому, что вы обычно понимаете. Он представляет процент доступного процессора, а не объем его использования. Если программы используют 5% ЦП, то SIP покажет, что использует 95% ЦП, или 95% ЦП не используется или нежелателен другими потоками в системе.
Но мой компьютер медленный!
Если ваш компьютер работает медленно, и вы заметили высокую загрузку процесса простоя системы — ну, это не ошибка процесса простоя системы. Поведение этого процесса совершенно нормально и предполагает, что проблема не в высокой загрузке процессора. Это может быть вызвано нехваткой памяти, медленным хранением или чем-то еще, из-за использования ресурсов вашего компьютера. Как всегда, рекомендуется запустить сканирование с помощью антивирусной программы, если у вас возникли проблемы, и вы не запускаете ничего, что может замедлить работу вашего компьютера.
Process Handles and Identifiers
When a new process is created by the CreateProcess function, handles of the new process and its primary thread are returned. These handles are created with full access rights, and — subject to security access checking — can be used in any of the functions that accept thread or process handles. These handles can be inherited by child processes, depending on the inheritance flag specified when they are created. The handles are valid until closed, even after the process or thread they represent has been terminated.
The CreateProcess function also returns an identifier that uniquely identifies the process throughout the system. A process can use the GetCurrentProcessId function to get its own process identifier (also known as the process ID or PID). The identifier is valid from the time the process is created until the process has been terminated. A process can use the Process32First function to obtain the process identifier of its parent process.
If you have a process identifier, you can get the process handle by calling the OpenProcess function. OpenProcess enables you to specify the handle’s access rights and whether it can be inherited.
A process can use the GetCurrentProcess function to retrieve a pseudo handle to its own process object. This pseudo handle is valid only for the calling process; it cannot be inherited or duplicated for use by other processes. To get the real handle to the process, call the DuplicateHandle function.
How to get process id by its service name with a script to variable
I have service named WinDefend and it runs on process svchost.exe
There other many svchost.exe processes and I need to find a way to get its ID.
when I run tasklist /svc I can see:
I am not sure how can I get it.
I found this command but when I tried the select «PID» it gave me empty column.
I need to get the PID of the process to variable.
6 Answers 6
tasklist is just returning text, not actual objects that have properties you can access. You can use WMI to get this information instead:
Annoying as this is, it requires you to set a unique title for your script if you want the pid for the current process. Then search for that unique title within the list of processes. Thankfully, the Title command allows you to do just that. Also see MagicAndi’s response.
Here is my batch file solution:
BTW, I’ve had the ‘pleasure’ of doing this time and time again over the years, via API, or batch, or ps. Pick your poison — on a Windows platform it’s all the same.
I found an even better way via powershell: $pid returns the current process’ process id.
An alternative way to get a process PID:
Or you can sum it up to:
Note: This will grab the first service that matches your $serviceName , if you run a service that runs several instances of itself (e.x. slack) you’ll only get the first pid. tasklist /v /fi «IMAGENAME eq slack.exe» /fo csv will return an array with each CSV line being an array entry. You can also filter this with findstr to avoid getting the column names.
EDIT: As WinDefend is a subservice of a program (In this case svchost.exe ) you may need to swap the verbose flag for tasklist to /svc like so:
alternatively search for the service’s name through a filter:
And taking into account that the filter returns a row of column names as well as the line you were looking for: