读取配置文件结束指定进程

读取配置文件结束指定进程

#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <windows.h>
#include <stdint.h>
#include <tlhelp32.h>
#include <iostream>
#include <vector>
#include <time.h>
#include <fstream>
//#pragma comment( linker, "/subsystem:windows /entry:mainCRTStartup" )
using namespace std;
char* time_now() //返回当前日期时间
{
time_t rawtime;
struct tm *info;
char buffer[]; time(&rawtime); info = localtime(&rawtime); strftime(buffer, , "%Y-%m-%d %H:%M:%S", info);
return buffer;
} DWORD GetProcessIdFromName(string name) //根据进程名称获取进程pid并返回进程pid
{
HANDLE hsnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, );
if (hsnapshot == INVALID_HANDLE_VALUE)
{
printf("CreateToolhelp32Snapshot Error!\n");
return ;
}
PROCESSENTRY32 pe;
pe.dwSize = sizeof(PROCESSENTRY32); int flag = Process32First(hsnapshot, &pe); while (flag != )
{
if (strcmp(pe.szExeFile, name.c_str()) == )
{
return pe.th32ProcessID;
}
flag = Process32Next(hsnapshot, &pe);
}
CloseHandle(hsnapshot);
return ;
} int KillProcess(int id) //根据进程ID杀进程
{
HANDLE hProcess = NULL;
hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, id); //打开目标进程
if (hProcess == NULL) {
//wprintf(L"\nOpen Process fAiled:%d\n", GetLastError());
return -;
}
else{
DWORD ret = TerminateProcess(hProcess, );
// printf("Kill OK!\n");
if (ret == ) {
// wprintf(L"%d", GetLastError()); }
}
//结束目标进程 return -;
} void write_file(const char* timenow, int p_id, const char* p_name)// 写配置文件
{ ofstream aa;
aa.open("c:/killconfig.log");
aa << "[" << timenow << "]" << "[" << p_id << "]" << "[" << p_name << "]" <<"已被结束!"<< endl;
aa.close();
}
void ReadConfig()// 读取配置文件
{ string ppp;
ifstream ff;
ff.open("/config.ini");
while (getline(ff,ppp))
{
int a = GetProcessIdFromName(ppp.c_str());
if (a == NULL)
{
//printf("未检测到要结束的进程!\n");
continue;
}
else
{
KillProcess(a);
char* now_time = time_now();
write_file(now_time, a, ppp.c_str());//写入配置文件
printf("[%s][%d][%s]已经被结束!\n",now_time, a, ppp.c_str()); //日志打印 }
}
ff.close();
} int main()
{ while (){ ReadConfig();
Sleep(); //循环检测
} return ;
}

主要功能:  读取配置文件结束指定进程 每秒循环一次,并在C盘成成killconfig.log记录日志

05-16 08:10