Windows get the pid

Get the PID of a Windows service

Could anyone help me to know how to get the PID of a Windows service?
I need to get the PID in order to run the following command:

3 Answers 3

Assuming you know the name of the EXE the service uses and there is exactly one of them:

The method Process.GetProcessesByName(«yourservice») returns an Array of Processes with your specified name, so in case you don’t know how much of «yourservice.exe» runs simultaneously you might need a foreach loop.

What the other answers neglect is the fact that a single process can also host multiple, autonomous services. The multiple instances of the svchost.exe process, each hosting a couple of services, is the best example.

So in general, it is absolutely unsafe to try to kill an arbitrary service by killing it’s hosting process (I assume that is what you attempt to do, since you refer to taskkill.exe ). You might take down several unrelated services in the process.

If you do know that the service’s process only hosts the service you care about, than you can choose the strategy as suggested by @M C in his/her answer.

Alternatively, you can also use the ServiceController class to open a handle to your service and then use it (via the ServiceHandle property) to P/Invoke the QueryServiceStatusEx function to find out the Process ID you want to know.

If you need more details, you should clarify what it is that you’re actually trying to achieve. It is not clear from your question.

Update Here is some code I ripped out of an existing project that should do what you want, given you have a ServiceController instance. _As said above, use with care!__

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.

Читайте также:  Windows 10 загружается только без проверки подписи драйверов

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.

How to get PID from PHP function exec() in Windows?

I have always used:

But I am using an XP virtual machine to develop a web app and I have no idea how to get the pid in windows.

I tried this on a cmd:

And it gets the file executed, but the output is «$!»

How can I get the pid into the var $pid? (using php)

4 Answers 4

You will have to install an extra extension, but found the solution located at Uniformserver’s Wiki.

UPDATE

After some searching you might look into tasklist which coincidently, you may be able to use with the PHP exec command to get what you are after.

Читайте также:  Windows 10 problems with fonts

I’m using Pstools which allows you to create a process in the background and capture it’s pid:

It’s a little hacky, but it gets the job done

I landed here thanks to google and decided that this ten years old post needs more info based on How to invoke/start a Process in PHP and kill it using Process ID.

Imagine that you want to execute a command (this example uses ffmpeg to stream a file on a windows system to a rtmp server). You could command something like this:

The first part is explained here and the last part of that command outputs to files with that name for logging purposes:

So lets assume that that command works. You tested it. To run that command with php you can execute it with exec but it will take time (another subject, check set_time_limit), its a video handled by ffmpeg via php. Not the way to go but it is happening in this case.

You can run the command in background but what is the pid of that Process? We want to kill it for some reason and psexec gives only the ‘process ID» runned by a user. And there is only one user in this case. We want multiple processes on the same user.

Here is a example to get the pid of a runned process in php:

The code above should echo the pid of the ‘inBackground’ runned process.

Note that you need to save the pid to kill it later if it is still running.

Now you can do this to kill the process: (imagine the pid is 1234)

Here is my first post ever here on stackoverflow, I hope this will help someone. Have a awesome and not lonely christmas ♪♪

How to get own process pid from the command prompt in Windows

I’m trying to find a way to get my own PID from a command prompt (for later use in bat scripts).

So far the only useful way I found was to use getpids.exe from here : http://www.scheibli.com/projects/getpids/index.html, but I’m looking for a command that’s «built in» to Windows.

I’m looking for a «bullet proof» way. No assumptions about my process being the only cmd.exe or anything.

13 Answers 13

Since none of the other solutions are bulletproof and built in, I figured I’d offer the following solution, but note that you’ll need to parse/save the results somehow:

Expanding upon Tony Roth’s answer:

Using the WINDOWTITLE filter avoids the pipe so you can put it in a for loop and assign it to a variable with SET if you like:

Читайте также:  Астра линукс сервер печати

Removing the /v makes it quicker, and the /NH gets rid of the header line. You need the wildcard after «uniqueTitle» because the window title actually contains the current command (thus it would go on and on if you tried to match it fully).

Using PowerShell + WMI :

(as always, double the % sign with for in batch files)

I believe the following is bulletproof, provided the user has access to WMIC and TEMP points to a valid path where the user has write privileges. This is the end result of some collaborative work at http://www.dostips.com/forum/viewtopic.php?f=3&t=6133.

The script establishes an exclusive lock on a temporary file that incorporates the current time into the name. There can only be a collision if two like named batch processes attempt to get the PID within the same 0.01 second time interval, in which case only one will succeed.

Any process that fails will repeatedly loop back and try again with a new lock file path until it succeeds.

Получение Pid процесса

Получить PID процесса
Здравствуйте все! помогите кто чем может. ( Задача: Два разных процесса (А и В) запустили.

Получить по PID имя процесса
Здравствуйте! У меня проблема заключается в том, что есть PID нужного мне процесса, но имя самого.

Как узнать состояние процесса по PID?
Доброго времени суток, подскажите как можно узнать запущен ли процесс или не запущен если я знаю.

Как узнать заголовок окна по PID процесса
Тут Я скрываю окно по Заголовку программы. У меня не большой вопрос как узнать Заголовок окна на.

Я плохо разбираюсь в WMI и API, сделал примерно так. Но PID который я вывожу не меняется, подскажите пожалуйста где я ошибаюсь ? Место где я использовал EnumProcessModules выделено /////////////

Нужно вывести названия всех запущенных процессов и их ID

Добавлено через 1 минуту
Вот так ?

Решение

Решение

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Получение PID по щелчку
Подскажите пожалуйста, никак нельзя получить PID другого процесса, щелкнув мышью по окну, которое.

Определить заголовок(имя) окна, зная PID его процесса
Сабж! Уже 2ой день не могу найти — как? У меня известе PID и hwnd процесса, как узнать имя окна(то.

Зная pid процесса (либо его заголовок), развернуть окно приложения на полный экран
Друзья, всем привет! Подскажите, в каком направлении двигаться, и какие функции использовать. .

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

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