码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-02-17 16:02:19      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:当前日期   error   clu   hand   etl   ios   lag   使用   c++   

#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <windows.h>
#include <stdint.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <istream>
#include <ctime>
//#pragma comment( linker, "/subsystem:windows /entry:mainCRTStartup" )//隐藏命令行窗口

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(char *name) //根据进程名称获取进程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) == 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 ReadConfig()// 读取配置文件
{
       char p[100];   
        FILE* fp = fopen("/config.ini", "r");
           

        while (!feof(fp)) //按行读取进程名称,直到文件结束
        {
           
                fscanf(fp, "%s", p);
                int a = GetProcessIdFromName(p);
                if (a == NULL)
                {
                   // printf("未检测到要结束的进程!\n");

                }
                else
                {
                    KillProcess(a);
                   
                    printf("[%s]进程pid[%d],进程名称:%s已经被结束!\n",time_now(), a, p);
                }

           
        }
        fclose(fp);
}





int main()
{

    while (1){

        ReadConfig(); //读取配置文件
        Sleep(1000);
    }  

    return 0;
}

使用该代码编译后,需要在程序所在目录新建config.ini文件, 并在文本中输入需要结束的进程名称,一行一个,

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

标签:当前日期   error   clu   hand   etl   ios   lag   使用   c++   

原文地址:https://www.cnblogs.com/shenji/p/12321725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!