Windows start process with pid

Windows start process with pid

Сообщения: 162
Благодарности: 2

Типичное exe приложение серверного типа.
Запускаю при помощи start. Завершение через taskkill при помощи PID.

А вообе суть такая: Есть многопользовательский сайт на php,где в интерфейсе кнопки: старт, стоп.
При клике Старт формируется файл start.cmd, который содержит путь к запускаемому файлу, и сам запус этого файла, после exit и cmd.exe прекращает работу. Все было нормально, пока работало одно приложение. Но при запуске 2 и более уже по названию не отключить. Вот, хотел бы реализовать таким же образом его остановку: при клике на Стоп сайт формирует файл stop.exe, где содержит остановку процесса по PID.
p.s. Если получать Pid при запуске возникает еще одна проблема: как cmd.exe отправить php данные о pid’e, что бы тот знал какой именно PID принадлежит пользователю.

Сообщения: 26991
Благодарности: 7877

Паркан, сожалею, но с php помочь Вам не смогу. Насколько я понимаю, нажимают кнопки на клиенте, а приложение должно запускаться и останавливаться на сервере, так? Сеть глобальная или локальная? Как и где предполагаете хранить PID? Как планируется осуществлять идентификацию клиента, как — соотносить его с уже запущенным приложением (если, например, клиент просто запустит приложение и, не остановив его, выйдет; снова зайдёт, запустит и выйдет и т.д.)?

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

Общий принцип запуска приложения и получения его PID (на WSH):

Что и как Вы с полученным PID будете делать дальше — зависит от ответов на заданные в начале поста вопросы.

Завершение процесса по известному PID, например, переданному единственным аргументом:

How to capture the PID of a process when launching it from command line?

Is there a way to do this purely in a .bat file?

The purpose is to launch iexplore.exe , then kill just that instance when it’s finished.

8 Answers 8

Here’s what I use:

The directory is set to the directory that the cmd file is located in. Change dir to alter that. Modify cmd to change which command is run.

If you want a stop.cmd that kills it, it would look like this

you can use vbscript, here’s an example creating notepad, then terminating it using its pid

save as myscript.vbs and on command line

A slight variation on the answer provided by @kybernetikos since it has a parsing issue. Note the line if %%j gr 0 (

Most often you do know what task you start — in this case, which page iexplorer shall show.

It will kill all instances of something showing your page title, but with a specific title most often there should be exactly one.

For some reason your approach of getting process id did not work for me, but since I’m expert in batches, I’ve coded my own approach, attaching here:

I think you can’t do that with simple command line utilities, as IE actually spawns child processes for each tab, i.e. if IE is not yet running you would get one parent IE process and a child process for the tab, and if IE is already running you would simply get a single child process.

Читайте также:  All users windows rename

It will be even quite tricky when you write your own tool to kill IE because when you kill a child (tab) process, IE will automatically recover this tab.

See also this related question: How to obtain process of newly created IE8 window? (though there is no good answer there).

Find the PID of a process that uses a port on Windows

My service crash on startup with the classic:

How can I find the process for killing it?

7 Answers 7

Just open a command shell and type (saying your port is 123456):

You will see everything you need.

The headers are:

Find the PID of a process that uses a port on Windows (e.g. port: «9999»)

-a Displays all connections and listening ports.

-o Displays the owning process ID associated with each connection.

-n Displays addresses and port numbers in numerical form.

Then kill the process by PID

/F — Specifies to forcefully terminate the process(es).

Note: You may need an extra permission (run from administrator) to kill some certain processes

Command:

Output:

Now cut the process ID, «10396», using the for command in Windows.

Command:

Output:

If you want to cut the 4th number of the value means «LISTENING» then command in Windows.

Command:

Output:

If you want to do this programmatically you can use some of the options given to you as follows in a PowerShell script:

However; be aware that the more accurate you can be the more precise your PID result will be. If you know which host the port is supposed to be on you can narrow it down a lot. netstat -aon | findstr «0.0.0.0:9999» will only return one application and most llikely the correct one. Only searching on the port number may cause you to return processes that only happens to have 9999 in it, like this:

The most likely candidate usually ends up first, but if the process has ended before you run your script you may end up with PID 12331 instead and killing the wrong process.

Управление процессами с помощью командлетов Process Managing Processes with Process Cmdlets

Командлеты Process в Windows PowerShell позволяют управлять локальными и удаленными процессами в Windows PowerShell. You can use the Process cmdlets in Windows PowerShell to manage local and remote processes in Windows PowerShell.

Получение процессов (Get-Process) Getting Processes (Get-Process)

Для получения процессов, запущенных на локальном компьютере, выполните командет Get-Process без параметров. To get the processes running on the local computer, run a Get-Process with no parameters.

Отдельные процессы можно получить, указав их имена или идентификаторы. You can get particular processes by specifying their process names or process IDs. Следующая команда возвращает процесс Idle: The following command gets the Idle process:

То, что в некоторых ситуациях командлеты не возвращают данные, является нормальным. Однако если при указании процесса по его идентификатору Get-Process не находит совпадений, он выдает ошибку, так как стандартной целью является получение известного выполняющегося процесса. Although it is normal for cmdlets to return no data in some situations, when you specify a process by its ProcessId, Get-Process generates an error if it finds no matches, because the usual intent is to retrieve a known running process. Если процесс с указанным идентификатором отсутствует, весьма вероятно, что идентификатор неправильный или нужный процесс уже завершился: If there is no process with that Id, it is likely that the Id is incorrect or that the process of interest has already exited:

Читайте также:  Переименование контроллера домена windows 2016

Параметр Name командлета Get-Process можно использовать для указания подмножества процессов на основе имени процесса. You can use the Name parameter of the Get-Process cmdlet to specify a subset of processes based on the process name. Параметр Name может принимать несколько имен в виде списка с разделителями-запятыми и поддерживает использование подстановочных знаков, что позволяет задавать шаблоны имен. The Name parameter can take multiple names in a comma-separated list and it supports the use of wildcards, so you can type name patterns.

Например, следующая команда возвращает процессы, имена которых начинаются с «ex.». For example, the following command gets process whose names begin with «ex.»

Поскольку класс System.Diagnostics.Process .NET является основой для процессов Windows PowerShell, он удовлетворяет некоторым соглашениям, используемым System.Diagnostics.Process. Because the .NET System.Diagnostics.Process class is the foundation for Windows PowerShell processes, it follows some of the conventions used by System.Diagnostics.Process. Одно из таких соглашений требует, чтобы имя процесса для исполняемого файла никогда не содержало «.exe» в конце имени этого файла. One of those conventions is that the process name for an executable never includes the «.exe» at the end of the executable name.

Get-Process также принимает несколько значений для параметра Name. Get-Process also accepts multiple values for the Name parameter.

Параметр ComputerName командлета Get-Process можно использовать для получения процессов на удаленных компьютерах. You can use the ComputerName parameter of Get-Process to get processes on remote computers. Например, следующая команда получает процессы PowerShell на локальном (представленным «localhost») и двух удаленных компьютерах. For example, the following command gets the PowerShell processes on the local computer (represented by «localhost») and on two remote computers.

Имена компьютеров в этих данных не указаны, однако они хранятся в свойстве MachineName объектов процесса, возвращаемых Get-Process. The computer names are not evident in this display, but they are stored in the MachineName property of the process objects that Get-Process returns. Следующая команда использует командлет Format-Table для отображения свойств ID, ProcessName и MachineName (ComputerName) объектов процесса. The following command uses the Format-Table cmdlet to display the process ID, ProcessName and MachineName (ComputerName) properties of the process objects.

Эта более сложная команда добавляет в стандартные отображаемые данные Get-Process свойство MachineName. This more complex command adds the MachineName property to the standard Get-Process display.

Остановка процессов (Stop-Process) Stopping Processes (Stop-Process)

Windows PowerShell позволяет гибко выводить списки процессов, но как обстоят дела с остановкой процесса? Windows PowerShell gives you flexibility for listing processes, but what about stopping a process?

Командлет Stop-Process принимает имя или идентификатор, указывающие останавливаемый процесс. The Stop-Process cmdlet takes a Name or Id to specify a process you want to stop. Возможность остановки процессов зависит от ваших разрешений. Your ability to stop processes depends on your permissions. Некоторые процессы остановить нельзя. Some processes cannot be stopped. Например, при попытке остановить неактивный процесс возникает ошибка: For example, if you try to stop the idle process, you get an error:

Можно также принудительно вывести запрос с помощью параметра Confirm . You can also force prompting with the Confirm parameter. Он особенно удобен при использовании подстановочного знака в имени процесса, так как случайно может быть определено соответствие с некоторыми процессами, которые не нужно останавливать: This parameter is particularly useful if you use a wildcard when specifying the process name, because you may accidentally match some processes you do not want to stop:

Сложную обработку процессов можно реализовать с помощью командлетов фильтрации объектов. Complex process manipulation is possible by using some of the object filtering cmdlets. Так как объект Process имеет свойство Responding, которое равно true, если он перестал отвечать, вы можете остановить все неотвечающие приложения с помощью следующей команды: Because a Process object has a Responding property that is true when it is no longer responding, you can stop all nonresponsive applications with the following command:

Читайте также:  Приложение для nat windows 10

Аналогичный подход возможен и в других ситуациях. You can use the same approach in other situations. Предположим, например, что приложение дополнительной области уведомлений запускается автоматически при открытии другого приложения. For example, suppose a secondary notification area application automatically runs when users start another application. Эта процедура может работать неправильно в сеансах служб терминалов, однако вам все равно нужно сохранить ее в сеансах, выполняемых в консоли физического компьютера. You may find that this does not work correctly in Terminal Services sessions, but you still want to keep it in sessions that run on the physical computer console. Сеансы, подключенные к рабочему столу физического компьютера, всегда имеют идентификатор сеанса 0, поэтому можно остановить все экземпляры процесса, находящиеся в других сеансах, с помощью Where-Object и SessionId процесса: Sessions connected to the physical computer desktop always have a session ID of 0, so you can stop all instances of the process that are in other sessions by using Where-Object and the process, SessionId :

Командлет Stop-Process не использует параметр ComputerName. The Stop-Process cmdlet does not have a ComputerName parameter. Поэтому для выполнения команды остановки процесса на удаленном компьютере необходимо использовать командлет Invoke-Command. Therefore, to run a stop process command on a remote computer, you need to use the Invoke-Command cmdlet. Например, чтобы остановить процесс PowerShell на удаленном компьютере Server01, введите: For example, to stop the PowerShell process on the Server01 remote computer, type:

Остановка всех остальных сеансов Windows PowerShell Stopping All Other Windows PowerShell Sessions

В некоторых случаях может пригодиться возможность остановки всех выполняющихся сеансов Windows PowerShell, отличных от текущего. It may occasionally be useful to be able to stop all running Windows PowerShell sessions other than the current session. Если сеанс использует слишком много ресурсов или недоступен (он может выполняться удаленно или в другом сеансе), возможно, остановить его напрямую не получится. If a session is using too many resources or is inaccessible (it may be running remotely or in another desktop session), you may not be able to directly stop it. При попытке остановить все выполняющиеся сеансы может быть завершен текущий сеанс. If you try to stop all running sessions, however, the current session may be terminated instead.

Каждый сеанс Windows PowerShell имеет переменную среды PID, содержащую идентификатор процесса Windows PowerShell. Each Windows PowerShell session has an environment variable PID that contains the Id of the Windows PowerShell process. Можно проверить переменную $PID на наличие идентификатора каждого сеанса и завершить только сеансы Windows PowerShell с другим идентификатором. Следующая команда конвейера делает именно это и возвращает список завершенных сеансов (из-за использования параметра PassThru ): You can check the $PID against the Id of each session and terminate only Windows PowerShell sessions that have a different Id. The following pipeline command does this and returns the list of terminated sessions (because of the use of the PassThru parameter):

Запуск, отладка и ожидание процессов Starting, Debugging, and Waiting for Processes

Windows PowerShell также имеет командлеты для запуска (или перезапуска), отладки процесса и ожидания завершения процесса перед выполнением команды. Windows PowerShell also comes with cmdlets to start (or restart), debug a process, and wait for a process to complete before running a command. Дополнительные сведения об этих командлетах см. в разделах справки по каждому из них. For information about these cmdlets, see the cmdlet help topic for each cmdlet.

Оцените статью