目前正在做的项目中有个需求,要通过进程名查找进程,其主要实现代码是函数findProcessByName。
代码如下:
int findProcessByName(const string& name)
{
int count{ 0 };
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE)
{
return count;
}
PROCESSENTRY32 pe;
pe.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hSnap, &pe))
{
CloseHandle(hSnap);
return count;
}
do
{
if (string(pe.szExeFile) == name)
{
++count;
}
} while (Process32Next(hSnap, &pe));
CloseHandle(hSnap);
return count;
}
可执行的完整代码如下:
checkProcess.h
#pragma once
#include <Windows.h>
#include <tlhelp32.h>
#include <string>
#include <iostream>
using namespace std;
int findProcessByName(const string& name)
{
int count{ 0 };
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE)
{
return count;
}
PROCESSENTRY32 pe;
pe.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hSnap, &pe))
{
CloseHandle(hSnap);
return count;
}
do
{
if (string(pe.szExeFile) == name)
{
++count;
}
} while (Process32Next(hSnap, &pe));
CloseHandle(hSnap);
return count;
}
void checkProcess()
{
string name { "Code.exe" };
int count = findProcessByName(name);
if ( count == 0 )
{
cout << "Cannot find specified process." << endl;
return;
}
cout << "Find specified process " << name << "!" << endl;
cout << "Count of them: " << count << "." << endl;
}
main.cpp
#include "checkprocess.h"
int main()
{
checkProcess();
return 0;
}
运行效果
Windows中可以通过命令 taskkill 结束进程。
比如,通过进程名结束进程:
taskkill /f /im Code.exe
关于taskkill的更多信息,可以cmd.exe窗口中通过如下命令查看
taskkill /?
或者(上面的写法是官方提示的用法)
taskkill/?
查看windows的所有命令
help
每一次记录就是一次收获!
养成习惯,以前就是没有这种好习惯,以后要坚持!