CreateProcess執行控制檯程序,並獲取輸出

void StartProcess(LPCWSTR program, LPCWSTR args)
{
	const int MY_PIPE_BUFFER_SIZE = 1024;
	//初始化管道
	HANDLE hPipeRead;
	HANDLE hPipeWrite;
	SECURITY_ATTRIBUTES saOutPipe;
	::ZeroMemory(&saOutPipe, sizeof(saOutPipe));
	saOutPipe.nLength = sizeof(SECURITY_ATTRIBUTES);
	saOutPipe.lpSecurityDescriptor = NULL;
	saOutPipe.bInheritHandle = TRUE;
	if (CreatePipe(&hPipeRead, &hPipeWrite, &saOutPipe, MY_PIPE_BUFFER_SIZE))
	{
		PROCESS_INFORMATION processInfo;
		::ZeroMemory(&processInfo, sizeof(processInfo));
		STARTUPINFO startupInfo;
		::ZeroMemory(&startupInfo, sizeof(startupInfo));
		startupInfo.cb = sizeof(STARTUPINFO);
		startupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
		startupInfo.hStdOutput = hPipeWrite;
		startupInfo.hStdError = hPipeWrite;
		startupInfo.wShowWindow = SW_HIDE;

		//startupInfo.dwFlags = STARTF_USESHOWWINDOW;
		//startupInfo.hStdOutput = hPipeWrite;
		//startupInfo.hStdError = hPipeWrite;
		//startupInfo.wShowWindow = SW_HIDE;
		int ret;
		//while(TRUE)
		
		ret = ::CreateProcess(program, (LPWSTR)args,
			NULL,  // process security
			NULL,  // thread security
			TRUE,  //inheritance
			0,     //no startup flags
			NULL,  // no special environment
			NULL,  //default startup directory
			&startupInfo,
			&processInfo);
        //個人發現不加 sleep 進程啓動有時候會失敗,不清楚具體原因
		::Sleep(1000);
		WaitForSingleObject(processInfo.hProcess, 3000);
		if (ret == 0)
		{
			int nRet = GetLastError();
			printf("CreateProcess last error %d \n", nRet);
		}
		else
		{
			DWORD dwReadLen = 0;
			DWORD dwStdLen = 0;
			if (PeekNamedPipe(hPipeRead, NULL, 0, NULL, &dwReadLen, NULL) && dwReadLen > 0)
			{
				char szPipeOut[MY_PIPE_BUFFER_SIZE];
				::ZeroMemory(szPipeOut, sizeof(szPipeOut));
				if (ReadFile(hPipeRead, szPipeOut, dwReadLen, &dwStdLen, NULL))
				{
					string s = string(szPipeOut);
					if (s.npos != s.find("True"))
					{
						printf("Recog Yes \n");
					}
					else
					{
						printf("Recog NO \n");
					}
				}
			}
	
		}
		if (processInfo.hProcess)
		{
			CloseHandle(processInfo.hProcess);
		}
		if (processInfo.hThread)
		{
			CloseHandle(processInfo.hThread);
		}
	}
	CloseHandle(hPipeRead);
	CloseHandle(hPipeWrite);
}



void ThriftUdpServer::CreatePyProcess(string userID)
{

    wchar_t program[MAX_PATH];// = TEXT("D:\\ProgramData\\Anaconda3\\python.exe");
    wchar_t args[MAX_PATH]; // = TEXT(" E:\\wqs\\Python\\recognition.py 610124198705273325 E:\\wqs\\vc10\\PCMUdpServer\\PCMUdpServer\\610124198805273130.jpg recog E:\\FaceData\\FaceEncodingDir\\  E:\\FaceData\\FaceImage\\");
    

    wsprintf(program, L"D:\\ProgramData\\Anaconda3\\python.exe");
    wsprintf(args, L" E:\\wqs\\Python\\recognition.py \
        %s \
        %s.jpg \
        recog \
        %s \
        %s",multiByteToWideChar(userID), multiByteToWideChar(userID), FaceEncodingDir, FaceImageDir);

    StartProcess(program, args);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章