프로그램 명을 가지고, 프로세스 ID 알아내기 (Get Process ID from Program Name)
절름발이 프로그래머/C언어, C++ 과 Visual C++ / 2010. 10. 31. 01:56
Linux 에서는 /proc 구조를 뒤져서 알아낼 수 있고,
Windows에서도 비슷하게 프로세스들을 일일히 뒤져서 알아낸다.
Linux 에서 쓰는 방법 (출처 : http://www.linuxforums.org/forum/programming-scripting/40078-c-printing-linux-process-table.html)
#include <stdio.h>
#include <dirent.h>
#include <string.h>
unsigned int getProcessID(char *p_processname) {
DIR *dir_p;
struct dirent *dir_entry_p;
char dir_name[40]; // ??? buffer overrun potential
char target_name[252]; // ??? buffer overrun potential
int target_result;
char exe_link[252];
int errorcount;
int result;
errorcount=0;
result=0;
dir_p = opendir("/proc/"); // Open /proc/ directory
while(NULL != (dir_entry_p = readdir(dir_p))) { // Reading /proc/ entries
if (strspn(dir_entry_p->d_name, "0123456789") == strlen(dir_entry_p->d_name)) { // Checking for numbered directories
strcpy(dir_name, "/proc/");
strcat(dir_name, dir_entry_p->d_name);
strcat(dir_name, "/"); // Obtaining the full-path eg: /proc/24657/
exe_link[0] = 0;
strcat(exe_link, dir_name);
strcat(exe_link, "exe"); // Getting the full-path of that exe link
target_result = readlink(exe_link, target_name, sizeof(target_name)-1); // Getting the target of the exe ie to which binary it points to
if (target_result > 0) {
target_name[target_result] = 0;
if (strstr(target_name, p_processname) != NULL) { // Searching for process name in the target name -- ??? could be a better search !!!
result = atoi(dir_entry_p->d_name);
printf("getProcessID(%s) :Found. id = %d\n", p_processname, result);
closedir(dir_p);
return result;
}
}
}
}
closedir(dir_p);
printf("getProcessID(%s) : id = 0 (could not find process)\n", p_processname);
return result;
}
Windows 에서 쓰는 방법 (출처 : http://cboard.cprogramming.com/cplusplus-programming/91038-process-id-exe.html)
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <string>
#include "psapi.h"
DWORD GetProcessByFileName(char* name){
DWORD process_id_array[1024];
DWORD bytes_returned;
DWORD num_processes;
HANDLE hProcess;
char image_name[256];
char buffer[256];
int i;
DWORD exitcode;
EnumProcesses(process_id_array, 256*sizeof(DWORD), &bytes_returned);
num_processes = (bytes_returned/sizeof(DWORD));
for (i = 0; i < num_processes; i++) {
hProcess=OpenProcess(PROCESS_ALL_ACCESS,TRUE,process_id_array[i]);
if(GetModuleBaseName(hProcess,0,image_name,256)){
if(!stricmp(image_name,name)){
CloseHandle(hProcess);
return process_id_array[i];
}
}
CloseHandle(hProcess);
}
return 0;
}
void __cdecl main(int argc, char *argv[])
{
DWORD dwPID;
dwPID = GetProcessByFileName("calc.exe");
printf("%lu", (unsigned long)dwPID);
return;
}