CreateProcess创建一个标准进程,打开pword程序,PROCESS_INFORMATION接收新进程的相关信息,如果不要新进程的句柄的话,应将该值设为NULL。当创建进程终止时,应该关闭PROCESS_INFORMATION结构体返回的进程和线程句柄,防止内存泄漏。
关闭进程:
a:如果进程是自己创建的,可以使用进程间通信的方法来通知这个进程来结束自己
b:向该进程的主窗口发送一个WM_CLOSE消息
c:使用GetExitCodeProcess和TerminateProcess函数,如果进程仍在运行的话,GetExitCodeProcess将返回STILL_ACTIVE
// MyProcess.cpp : Defines the entry point for the console application. //
#include "stdafx.h" #include <windows.h> #include <commctrl.h>
int _tmain(int argc, _TCHAR* argv[]) { BOOL fSuccess; PROCESS_INFORMATION pi; DWORD dwExitCode;
fSuccess = CreateProcess(TEXT("pword"),NULL,NULL,NULL,FALSE,0,NULL,NULL,NULL,&pi); if(fSuccess) { printf("create process success/r/n"); } else { printf("create process error/r/n"); goto cleanup; }
Sleep(5000);
fSuccess = GetExitCodeProcess(pi.hProcess,&dwExitCode); if(STILL_ACTIVE == dwExitCode) { printf("process pword still active/r/n"); }
if(NULL == fSuccess) { printf("GetExitCodeProcess pword error/r/n"); goto cleanup; } else { printf("GetExitCodeProcess pword success/r/n"); }
fSuccess = TerminateProcess(pi.hProcess,dwExitCode); if(NULL == fSuccess) { printf("TerminateProcess pword error/r/n"); goto cleanup; } else { printf("TerminateProcess pword success/r/n"); }
cleanup: CloseHandle(pi.hThread); CloseHandle(pi.hProcess);
return 0; } |