Find a Process Id by Name

How to get PID of process by specifying process name and store it in a variable to use further?

If you want to kill -9 based on a string (you might want to try kill first) you can do something like this:

ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}'

This will show you what you're about to kill (very, very important) and just pipe it to sh when the time comes to execute:

ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}' | sh

Find Process Name by its Process ID

The basic one, ask tasklist to filter its output and only show the indicated process id information

tasklist /fi "pid eq 4444" 

To only get the process name, the line must be splitted

for /f "delims=," %%a in ('
tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a

In this case, the list of processes is retrieved without headers (/nh) in csv format (/fo:csv). The commas are used as token delimiters and the first token in the line is the image name

note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command

for /f "delims=," %%a in ('
tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a

This will generate the task list and filter it searching for the process id in the second column of the csv output.

edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.

tasklist /fi "idp eq 4444" 

Fast way to find process id by name

for get process id by name need enumerate processes and compare it names with given. how minimum i not listen about ready system api which just do this (and without enumeration internal). of course need understand that do this exist sense primary for system level debug tools - the name of process not reliable. can be many processes with same name, etc.

the fastest low-level way do this - use NtQuerySystemInformation function with SystemProcessInformation information class. all other ways - based on this api. but have significant overhead and losing info.

the CreateToolhelp32Snapshot - internal call NtQuerySystemInformation function with SystemProcessInformation but use section ( file mapping on win32 language) as storage for information. copy data tho this section and unmap it. the Process32First Process32Next - all time map section to memory again, copy data to your buffer (and drop some data in this process) and then unmap section. all this serious overhead. of course if you only once do this - you not view different, but if do this many time - different in speed will be visible.

the EnumProcesses of course also use NtQuerySystemInformation function with SystemProcessInformation but from all returned information - pass only process identifier for each process, and drop all another info. as result you need call OpenProcess and query it image path - again serious overhead and you can not open say protected processes.

of course here i described only current implementation. may be it will changed. may be not. however this is explain why NtQuerySystemInformation is fastest.

so documented it or no, "supported" or no - the NtQuerySystemInformation is fastest way, if use it correct.

may be altered or unavailable in future versions of Windows

this is written already 20 years. but still false. i personally sure that this api never will be altered or unavailable (how minimum not early than CreateToolhelp32Snapshot and EnumProcesses also will be altered or unavailable) - this is one of fundamental system api. no any reason do this.

This function has no associated import library. You must use the
LoadLibrary and GetProcAddress functions to dynamically link to
Ntdll.dll.

this is also lie. exist even 2 lib from wdk - ntdll.lib and ntdllp.lib (here more api but this lib can conflict with crt in some case if you use crt - multiple defined symbols) - so we can, but not need use LoadLibrary and GetProcAddress (very interesting for me - how we can call LoadLibrary and GetProcAddress without before call LoadLibrary and GetProcAddress for get addresses of LoadLibrary and GetProcAddress).

really NtQuerySystemInformation usual api function and called as any usual api function. all what we need - declaration for compiler and lib file for linker. lib exist in wdk (and always was here), despite msdn say another

example of usage

NTSTATUS GetProcessIdByName(PCUNICODE_STRING ImageName, HANDLE& UniqueProcessId)
{
NTSTATUS status;

ULONG cb = 0x10000;

UniqueProcessId = 0;

do
{
status = STATUS_INSUFFICIENT_RESOURCES;

if (PVOID buf = new UCHAR[cb])
{
if (0 <= (status = NtQuerySystemInformation(SystemProcessInformation, buf, cb, &cb)))
{
status = STATUS_NOT_FOUND;

union {
PVOID pv;
PBYTE pb;
PSYSTEM_PROCESS_INFORMATION pspi;
};

pv = buf;
ULONG NextEntryOffset = 0;

do
{
pb += NextEntryOffset;

if (RtlEqualUnicodeString(ImageName, &pspi->ImageName, TRUE))
{
UniqueProcessId = pspi->UniqueProcessId;
status = STATUS_SUCCESS;
break;
}

} while (NextEntryOffset = pspi->NextEntryOffset);

}

delete [] buf;
}

} while (status == STATUS_INFO_LENGTH_MISMATCH);

return status;
}

note that because required buffer size is very volatile (all time new threads created/exited) - need cal this api in loop until we got not STATUS_INFO_LENGTH_MISMATCH status

note do while (NextEntryOffset = pspi->NextEntryOffset) loop - if do while loop - we lost last entry (latest spawned process in system). and ImageName - this is UNICODE_STRING - so not mandatory zero terminated. as result use string api which assume 0 terminated string - not correct here (work because in this struct really used 0 terminated string) correct use RtlEqualUnicodeString here or similar

also this code search process by name until first match name found. of course need understand that can be multiple processes with same name - for example svchost.exe. in real search we can possible use and another conditions, like sessionid, process token properties, command line, etc. this already is separate question and depend from requirements

Is there a way to find a process on top of the process id and name in c#

You could store the Process.StartTime property in addition to its ID. That should protect you in the case that the PID has been re-used since the new process would have a different start time to the one stored.

var process = Process.GetProcessById(id);

if (process.ProcessName == processName && process.StartTime == startTime)
{
//kill the process
}

I suspect the following does not apply since you're persisting process information, but if your application is continually monitoring these processes then you might consider using the Process.Exited event to receive notifications when a process exits rather than checking every so often, e.g.

process.EnableRaisingEvents = true;
process.Exited += (sender, args) => { /* Do something */ };

Getting the process id of a process using the process name in perl

Proc::Find::find_proc returns an reference to an Array, not an Array.

So the correct code would be:

 my $pids = find_proc(name => 'my-app-name'); 
foreach my $pid (@$pids) {
print "pid = $pid\n";
}
# or use
# print "pid = ". $pids->[0] . "\n";
# or
# print "pid = $pids->[0]\n";

How to find pid of a process by Python?

If you just want the pid of the current script, then use os.getpid:

import os
pid = os.getpid()

However, below is an example of using psutil to find the pids of python processes running a named python script. This could include the current process, but the main use case is for examining other processes, because for the current process it is easier just to use os.getpid as shown above.

sleep.py

#!/usr/bin/env python
import time
time.sleep(100)

get_pids.py

import os
import psutil

def get_pids_by_script_name(script_name):

pids = []
for proc in psutil.process_iter():

try:
cmdline = proc.cmdline()
pid = proc.pid
except psutil.NoSuchProcess:
continue

if (len(cmdline) >= 2
and 'python' in cmdline[0]
and os.path.basename(cmdline[1]) == script_name):

pids.append(pid)

return pids

print(get_pids_by_script_name('sleep.py'))

Running it:

$ chmod +x sleep.py

$ cp sleep.py other.py

$ ./sleep.py &
[3] 24936

$ ./sleep.py &
[4] 24937

$ ./other.py &
[5] 24938

$ python get_pids.py
[24936, 24937]


Related Topics



Leave a reply



Submit