欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

创建进程CreateProcess()函数的简单实用

程序员文章站 2022-05-12 17:58:28
...

创建进程方法:

	// lpCommandLine字符串的格式:“exe路径+空格+参数1+空格+参数2+……”
	CString sParam = ::GetInstance()->GetInstallPath();
	sParam += _T("Program2.exe ");   // argv[0] 参数0
	sParam += _T("params1 ");		// argv[1] 参数1
	sParam += _T(" ");
	sParam += _T("params2 ");				// argv[2]  参数2
	sParam += _T(" ");
	sParam += _T("params3 ");					// argv[3] 参数3

	STARTUPINFO startInfo;
	PROCESS_INFORMATION pinfo = { 0 };
	ZeroMemory(&startInfo, sizeof(startInfo));
	startInfo.cb = sizeof(startInfo);
	ZeroMemory(&pinfo, sizeof(pinfo));
	startInfo.dwFlags = STARTF_USESHOWWINDOW;
	startInfo.wShowWindow = SW_HIDE;
	BOOL bRet = CreateProcess(nullptr, sParam.GetBuffer(sParam.GetLength()), NULL, NULL, FALSE, 0, NULL, NULL, &startInfo, &pinfo);
	sParam.ReleaseBuffer();
	
	if (!bRet)
	{
		CString strFailure = _T("启动控制台程序失败:");
		strFailure += sParam;
		return ;
	}

	CloseHandle(pinfo.hProcess);
	CloseHandle(pinfo.hThread);

进程函数:

int _tmain(int argc, _TCHAR* argv[])
{
	CString strInstallPath;
	if (argc < 4)
	{
		_TCHAR szFullPath[MAX_PATH];
		::GetModuleFileName(NULL, szFullPath, MAX_PATH);
		strInstallPath = szFullPath;
		strInstallPath.TrimRight(_T("\\"));
		strInstallPath += _T("\\log");
		_tmkdir(strInstallPath);
		
		AfxmessageBox(_T("Program1.exe 缺少命令行参数!"));
		return 0;
	}

	strInstallPath = argv[0];
	int nLast = strInstallPath.ReverseFind(_T('\\'));
	strInstallPath = strInstallPath.Left(nLast);
	CString strPram1 = argv[1];
	CString strPram2 = argv[2];
	CString strPram3 = argv[3];
	………………………………
}