Меню Рубрики

Windows suspend process command line

PsSuspend v1.07

By Mark Russinovich

Published: June 29, 2016

Download PsTools (2.7 MB)

Introduction

PsSuspend lets you suspend processes on the local or a remote system, which is desirable in cases where a process is consuming a resource (e.g. network, CPU or disk) that you want to allow different processes to use. Rather than kill the process that’s consuming the resource, suspending permits you to let it continue operation at some later point in time.

Installation

Copy PsSuspend onto your executable path and type «pssuspend» with command-line options defined below.

Using PsSuspend

Running PsSuspend with a process ID directs it to suspend or resume the process of that ID on the local computer. If you specify a process name PsSuspend will suspend or resume all processes that have that name. Specify the -r switch to resume suspended processes.

Usage: pssuspend [- ] [-r] [\\computer [-u username] [-p password]]

Parameter Description
Displays the supported options.
-r Resumes the specified processes specified if they are suspended.
\\computer Specifies the computer on which the process you want to suspend or resume is executing. The remote computer must be accessible via the NT network neighborhood.
-uВ username If you want to suspend a process on a remote system and the account you are executing in does not have administrative privileges on the remote system then you must login as an administrator using this command-line option. If you do not include the password with the -p option then PsSuspend will prompt you for the password without echoing your input to the display.
-pВ password This option lets you specify the login password on the command line so that you can use PsSuspend from batch files. If you specify an account name and omit the -p option PsSuspend prompts you interactively for a password.
processВ id Specifies the process ID of the process you want to suspend or resume.
processВ name Specifies the process name of the process or processes you want to suspend or resume.

PsSuspend is part of a growing kit of Sysinternals command-line tools that aid in the administration of local and remote systems named PsTools.

Download PsTools (2.7 MB)

PsTools

PsSuspend is part of a growing kit of Sysinternals command-line tools that aid in the administration of local and remote systems named PsTools.

Runs on:

  • Client: Windows Vista and higher.
  • Server: Windows Server 2008 and higher.

—>

Источник

How to suspend/resume a process in Windows?

In Unix we can suspend a process execution temporarily and resume it with signals SIGSTOP and SIGCONT . How can I suspend a single-threaded process in Windows without programming ?

7 Answers 7

You can’t do it from the command line, you have to write some code (I assume you’re not just looking for an utility otherwise Super User may be a better place to ask). I also assume your application has all the required permissions to do it (examples are without any error checking).

Hard Way

First get all the threads of a given process then call the SuspendThread function to stop each one (and ResumeThread to resume). It works but some applications may crash or hung because a thread may be stopped in any point and the order of suspend/resume is unpredictable (for example this may cause a dead lock). For a single threaded application this may not be an issue.

Please note that this function is even too much naive, to resume threads you should skip threads that was suspended and it’s easy to cause a dead-lock because of suspend/resume order. For single threaded applications it’s prolix but it works.

Undocumented way

Starting from Windows XP there is the NtSuspendProcess but it’s undocumented. Read this post for a code example (reference for undocumented functions: news://comp.os.ms-windows.programmer.win32).

«Debugger» Way

To suspend a program is what usually a debugger does, to do it you can use the DebugActiveProcess function. It’ll suspend the process execution (with all threads all together). To resume you may use DebugActiveProcessStop .

This function lets you stop a process (given its Process ID), syntax is very simple: just pass the ID of the process you want to stop et-voila. If you’ll make a command line application you’ll need to keep its instance running to keep the process suspended (or it’ll be terminated). See the Remarks section on MSDN for details.

From Command Line

As I said Windows command line has not any utility to do that but you can invoke a Windows API function from PowerShell. First install Invoke-WindowsApi script then you can write this:

Of course if you need it often you can make an alias for that.

Источник

Управление процессами из командной строки

Способов управлять процессами в Windows предостаточно, и командная строка занимает в них далеко не первое место. Однако иногда бывают ситуации, когда все остальные инструменты кроме командной строки недоступны, например некоторые вредоносные программы могут блокировать запуск Task Manager и подобных ему программ. Да и просто для общего развития полезно знать способы управления компьютером из командной строки.

Для управления процессами в командной строке есть две утилиты — tasklist и taskkill. Первая показывает список процессов на локальном или удаленном компьютере, вторая позволяет их завершить. Попробуем …

Если просто набрать команду tasklist в командной строке, то она выдаст список процессов на локальном компьютере.

По умолчанию информация выводится в виде таблицы, однако ключ /fo позволяет задать вывод в виде списка или в формате CSV, а ключ /v показывает более подробную информацию о процессах, например команда tasklist /v /fo list выведет подробное описание всех процессов в виде списка.

Список получится довольно большой, поэтому попробуем уточнить запрос. Для этого используем ключ /fi , который позволяет использовать фильтры для вывода данных, например команда tasklist /fi ″username eq user″ /fi ″memusage le 40000″ выводит список процессов пользователя user, которые потребляют не больше 40Мб памяти.

Найдя процессы, которые необходимо завершить, воспользуемся командой taskkill. Завершать процессы можно по имени, идентификатору процесса (PID) или задав условия с помощью фильтров. Для примера запустим несколько экземпляров блокнота (notepad.exe) и попробуем завершить его разными способами.

Ключ /f завершает процесс принудительно, а /t завершает все дочерние процессы.

Полную справку по командам tasklist и taskkill можно получить, введя их с ключом /?

Теперь пустим в ход тяжелую артиллерию PowerShell. Его можно запустить не выходя из командной строки. Для получения списка процессов используем командлет Get-Process.

Чтобы не выводить весь список процессов можем воспользоваться командлетом Where-Object, который задает фильтр для выводимой информации. Для примера выведем список процессов, которые загружают процессор и отсортируем их по возрастанию нагрузки с помощью команды:

Get-Process | where <$_.cpu -gt 0>| sort cpu

С помощью PowerShell мы можем получить любую информацию о любом процессе. В качестве примера возьмем процесс cmd и выведем список его свойств командой:

Get-Process -Name cmd | Get-Member -Membertype property

Выбираем те свойства, что нам интересны ( в примере имя и ID процесса, путь к файлу, используемые модули и время запуска) и выводим их в виде списка командой:

Get-Process -Name cmd | Format-List name, id, path, modules, starttime

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

Для завершения процесса в PowerShell есть командлет Stop-Process. Он завершает указанный процесс по его имени или идентификатору. Однако мы поступим по другому и передадим результат выполнения командлета Get-Process по конвейеру:

Get-Process | where <$_.name -match ″notepad″>| Stop-Process

Get-Process не может показать процессы на удаленном компьютере, для этого воспользуемся командлетом Get-WmiObject , например посмотрим процессы на удаленном компьютере PC командой:

Get-WmiObject win32_process -computername PC | ft name, processid, description

Для боле полного ознакомления с PowerShell можно воспользоваться встроенной справкой, для вызова справки нужно набрать Get-Help ″имя командлета″

Ну и для полноты обзора рассмотрим еще одно средство для управления процессами из командной строки. Это утилиты Pslist и Pskill входящие в состав пакета PSTools от компании Sysinternals.

Эти утилиты не требуют специальной установки, достаточно просто скопировать их на диск. Для запуска нужно зайти в папку с утилитами и ввести в командной строке необходимую команду.

Pslist может выводить информацию о процессах по имени или ID, например командой pslist notepad -x выведем подробную информацию о нашем «многострадальном» блокноте.

Особенностью утилиты Pslist является режим task-manager. В этом режиме информация автоматически обновляется, причем можно задать время работы и интервал обновления. Запускается режим ключом -s , например командой tasklist -s -r 10 запускаем режим программу в режиме task-manager с обновлением раз в 10 сек.

Завершение процесса программой pskill предельно просто, вводим команду и имя (или ID) процесса и все.

Справку по утилитам Pslist и Pskill можно посмотреть, введя команду с ключом /?

И еще, все манипуляции с процессами необходимо выполнять с правами администратора, для этого командную строку требуется запускать с повышением привилегий.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Windows surface ipad rt
  • Windows support and help
  • Windows subsystem for linux beta
  • Windows style windows forms
  • Windows store что это такое