Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the process name in C++

How do I get the process name from a PID using C++ in Windows?

like image 362
Muhammad Avatar asked Dec 31 '10 12:12

Muhammad


People also ask

How do I find the PID process name?

In Windows, first click More details to expand the information displayed. From the Processes tab, select Details 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.

What is the command to display the name of a process?

You can use the ps command to find out which processes are running and display information about those processes. The ps command has several flags that enable you to specify which processes to list and what information to display about each process.

How do I get the current process name in Linux?

Type the ps aux to see all running process in Linux. Alternatively, you can issue the top command or htop command to view running process in Linux.


2 Answers

I guess the OpenProcess function should help, given that your process possesses the necessary rights. Once you obtain a handle to the process, you can use the GetModuleFileNameEx function to obtain full path (path to the .exe file) of the process.

#include "stdafx.h" #include "windows.h" #include "tchar.h" #include "stdio.h" #include "psapi.h" // Important: Must include psapi.lib in additional dependencies section // In VS2005... Project > Project Properties > Configuration Properties > Linker > Input > Additional Dependencies  int _tmain(int argc, _TCHAR* argv[]) {     HANDLE Handle = OpenProcess(         PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,         FALSE,         8036 /* This is the PID, you can find one from windows task manager */     );     if (Handle)      {         TCHAR Buffer[MAX_PATH];         if (GetModuleFileNameEx(Handle, 0, Buffer, MAX_PATH))         {             // At this point, buffer contains the full path to the executable         }         else         {             // You better call GetLastError() here         }         CloseHandle(Handle);     }     return 0; } 
like image 156
Salman A Avatar answered Oct 05 '22 23:10

Salman A


You can obtain the process name by using the WIN32 API GetModuleBaseName after having the process handle. You can get the process handle by using OpenProcess.

To get the executable name you can also use GetProcessImageFileName.

like image 37
Brian R. Bondy Avatar answered Oct 05 '22 22:10

Brian R. Bondy