25-进程的创建和使用

进程的创建和使用

函数CreateProcess来创建进程

参数:

  • lpCommandLine:打开进程的路径(主要配置的参数)

  • 其余保持默认即可(详见下面示例)

返回值:

  • 成功为1

  • 失败使用GetLastError()查看对应的错误码

案例

#include<stdio.h>
#include<Windows.h>

int RunExe()
{
TCHAR szCommandLine[] = L"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe";
STARTUPINFO strStartupInfo;
memset(&strStartupInfo, 0, sizeof(STARTUPINFO));
strStartupInfo.cb = sizeof(strStartupInfo);
PROCESS_INFORMATION szProcessInformation;
memset(&szProcessInformation, 0, sizeof(PROCESS_INFORMATION));

int bRet = CreateProcess(
NULL,
szCommandLine,
NULL,
NULL,
FALSE,
CREATE_NEW_CONSOLE,
NULL,
NULL,
&strStartupInfo,
&szProcessInformation
);

if (bRet)
{
printf("CreateSucess bRet = %d", bRet);
WaitForSingleObject(szProcessInformation.hProcess, 3000);
CloseHandle(szProcessInformation.hProcess);
CloseHandle(szProcessInformation.hThread);
szProcessInformation.hProcess = NULL;
szProcessInformation.hThread = NULL;
szProcessInformation.dwProcessId = NULL;
szProcessInformation.dwThreadId = NULL;
}
else
{
printf("Create Failed bRet = %d", bRet);
printf("errorcode = %d", GetLastError());
}
return 0;
}


int main()
{
printf("This is Chrome");
RunExe();
system("pause");
}