2014年3月21日18:17:21
维护进程定期(10s)检查工作进程是否存在。不存在,则创建工作进程。同时杀死多余的工作进程。
1、使用VS2008创建一个带预编译头的控制台项目。
2、源文件内容:
#include "stdafx.h"
#include <windows.h>
#include <psapi.h>
#include<iostream>
using namespace std;
#pragma once
#pragma message("Psapi.h --> Linking with Psapi.lib")
#pragma comment(lib,"Psapi.lib")
// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
// and compile with -DPSAPI_VERSION=1
bool cmpName_processID(TCHAR * pStrProcessName,DWORD processID)
{
TCHAR szProcessName[MAX_PATH] = TEXT("");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
&cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
CloseHandle( hProcess );
if(0 == _tcscmp(pStrProcessName,szProcessName))
{
return true;
}
return false;
}
void create_process(TCHAR * pStrProcessName)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( !CreateProcess(pStrProcessName, //module name
NULL, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
return;
}
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
return;
}
void check_create_process(TCHAR * pStrProcessName)
{
bool bExist = false;
DWORD aProcesses[1024], nByteNeed, nProcesses;
unsigned int i;
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &nByteNeed ) )
{
printf("获取所有进程失败\n");
return ;
}
// Calculate how many process identifiers were returned.
nProcesses = nByteNeed / sizeof(DWORD);
for ( i = 0; i < nProcesses; i++ )
{
if( aProcesses[i] != 0 )
{
if(cmpName_processID( pStrProcessName,aProcesses[i] ))
{
if(bExist)
{
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | // Required by Alpha
PROCESS_TERMINATE,
FALSE, aProcesses[i] );
if (NULL != hProcess )
{
TerminateProcess(hProcess, 0);
printf("杀死进程\n");
}
}
else
{
bExist = true;
}
}
}
}
if(bExist)return;
create_process(pStrProcessName);
}
int main( void )
{
char ch;
//cin>>ch;
while(1)
{
Sleep(10*1000);
check_create_process(_T("tt.exe"));
}
cin>>ch;
return 0;
}