作者:yurunsun@gmail.com 新浪微博@孙雨润 新浪博客 优快云博客日期:2012年11月4日
1. 进程main函数
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow);
- hInstance每个.exe .dll都被赋予了unique的instance handle,在需要加载资源的API中需要提供此Handle。
- hPrevInstance进程前一个实例的句柄,16位机器使用。
-
lpCmdLine
int nNumArgs; PWSTR *ppArgv = CommandLineToArgvW(GetCommandLineW(), &nNumArgs);
-
进程环境变量
PTSTR pEnvBlock = GetEnvironmentStringsW(); FreeEnvironmentStringsW(pEnvBlock); SetEnvironmentStringsW(LPWCH NewEnvironment); ExpandEnvironmentStringsW(LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize);
-
进程当前所在Drive和Dir
DWORD WINAPI GetCurrentDirectory(DWORD nBufferLength, LPTSTR lpBuffer); HRESULT SetCurrentDirectory(LPCOLESTR pszDir); DWORD GetFullPathName(...);
-
子进程 为了防止一个方法破坏现有堆栈,可以创建子进程,并同步等待子进程终止。
PROCESS_INFORMATION pi; DWORD dwExitCode; BOOL bSuccess = CreateProcess(..., &pi); if (bSuccess) { CloseHandle(pi.hThread); WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, &dwExitCode); CloseHandle(pi.hProcess); }
-
枚举进程性能 WindowsNT开发的PSAPI.dll中提供了一组API。
2. CreateProcess函数
BOOL WINAPI CreateProcess(
__in LPCTSTR lpApplicationName,
__in_out LPTSTR lpCommandLine,
__in LPSECURITY_ATTRIBUTES lpProcessAttributes,
__in LPSECURITY_ATTRIBUTES lpThreadAttributes,
__in BOOL bInheritHandles,
__in DWORD dwCreationFlags,
__in LPVOID lpEnvironment,
__in LPCTSTR lpCurrentDirectory,
__in LPSTARTUPINFO lpStartupInfo,
__out LPPROCESS_INFORMATION lpProcessInformation
);
- 名字、命令行
LPCTSTR
与LPTSTR
的区别。* lpProcessAttributes
、lpThreadAttributes
、bInheritHandles
指定安全性,NULL
或者SECURITY_ATTRIBUTES
;bInheritHandles
之前讨论过。dwCreationFlags
用于调试子进程lpEnvironment
新进程的环境变量lpCurrentDirectory
当前Drive/Dir
3. 终止进程
- 主线程入口点函数返回(Strong Recommanded)
ExitProcess/ExitThread
函数 会导致C/C++ 运行时库不能完成清理工作TerminateProcess
函数 异步函数,使用WaitForSingleObject
确保完成
4. Job
经常需要将一组进程当做单个实体处理,例如使用VS Build C++ Project时会生成若干Cl.exe。用户希望提前停止Build,VS必须能终止Cl.exe及所有子进程。
-
创建Job
HANDLE WINAPI CreateJobObject(LPSECURITY_ATTRIBUTES lpJobAttributes, LPCTSTR lpName);
-
将Process放入Job中
BOOL WINAPI AssignProcessToJobObject(HANDLE hJob, HANDLE hProcess);
-
对Job中的Process施加Restriction
BOOL WINAPI SetInformationJobObject(HANDLE hJob, JOBOBJECTINFOCLASS JobObjectInfoClass, LPVOID lpJobObjectInfo, DWORD cbJobObjectInfoLength);
-
终止Job中所有Process
BOOL WINAPI TerminateJobObject(HANDLE hJob, UINT uExitCode);