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

#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[80];

    time(&rawtime);

    info = localtime(&rawtime);

    strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info);
    return buffer;
}


DWORD GetProcessIdFromName(string name) //根据进程名称获取进程pid并返回进程pid
{
    HANDLE  hsnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hsnapshot == INVALID_HANDLE_VALUE)
    {
        printf("CreateToolhelp32Snapshot Error!\n");
        return 0;
    }
    PROCESSENTRY32 pe;
    pe.dwSize = sizeof(PROCESSENTRY32);

    int flag = Process32First(hsnapshot, &pe);

    while (flag != 0)
    {
        if (strcmp(pe.szExeFile, name.c_str()) == 0)
        {
            return pe.th32ProcessID;
        }
        flag = Process32Next(hsnapshot, &pe);
    }
    CloseHandle(hsnapshot);
    return 0;
}

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 -1;
    }
    else{
        DWORD ret = TerminateProcess(hProcess, 0);
       // printf("Kill OK!\n");
        if (ret == 0) {
         //   wprintf(L"%d", GetLastError());

        }
    }
    //结束目标进程

    return -1;
}

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 (1){

        ReadConfig();
        Sleep(1000); //循环检测
    }
    
    return 0;
}

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

posted @ 2020-02-17 14:45  神迹丶  阅读(393)  评论(0编辑  收藏  举报
网站已运行: