C语言杀掉一个进程

注:转载别人的代码,非常好用,非常感谢!!!

#include 
#include 
#pragma comment(lib,"Psapi.lib")
#include 
#include 

DWORD FindProcess(char *strProcessName)
{
	DWORD aProcesses[1024], cbNeeded, cbMNeeded;
	HMODULE hMods[1024];
	HANDLE hProcess;
	char szProcessName[MAX_PATH];

	if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )  return 0;

	for(int i=0; i< (int) (cbNeeded / sizeof(DWORD)); i++)
	{
		hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[i]);
		EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbMNeeded);
		GetModuleFileNameEx( hProcess, hMods[0], szProcessName,sizeof(szProcessName));

		if(strstr(szProcessName, strProcessName))
		{
			return(aProcesses[i]);
		}
	}

	return 0;
}

DWORD KillProcess(char *strProcessName)
{
	HANDLE TargetProcess = OpenProcess(PROCESS_TERMINATE, FALSE, FindProcess(strProcessName));

	if(TargetProcess == NULL)
	{
		return 0;
	}

	TerminateProcess(TargetProcess, 0);

	CloseHandle(TargetProcess);

	return 1;
}

int main(int argc, char *argv[])
{
	if (argc > 2)
	{
		if (strcmp(argv[1], "getpid") == 0)
		{
			DWORD dwRet = FindProcess(argv[2]);
			if (dwRet != 0)
			{
				printf("find success\n");
				return 0;
			}
			else
			{
				printf("find failed\n");
				return 0;
			}
		}
		else if (strcmp(argv[1], "kill") == 0)
		{
			DWORD dwRet = KillProcess(argv[2]);
			if (dwRet != 0)
			{
				printf("kill success\n");
				return 0;
			}
			else
			{
				printf("kill faild\n");
				return 0;
			}
		}
	}
	else
	{
		printf("参数输入错误\n");
		return 0;
	}

}
//注:得使用Psapi.lib 库





















你可能感兴趣的:(C++)