Преглед изворни кода

嵌入进程运行脚本:当线程结束时,需要恢复进程默认的标准输出;

scbc.sat2 пре 5 година
родитељ
комит
f12c129a6a

+ 3 - 1
RunPython/RunPython/RunPython.cpp

@@ -33,7 +33,9 @@ int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
 	{
 		// TODO: 在此处为应用程序的行为编写代码。
 		CScriptExecutor excutor;
-		excutor.InitScript("E:\\bin\\ScbcCopyKey\\ScbcTest.py", 
+		excutor.InitScript(
+			//"E:\\bin\\ScbcCopyKey\\ScbcTest.py", 
+			"D:\\SAT\\runner\\btc_runner_se\\runner\\output\\ODF_NPI_RT2841\\20191119172310094\\192.168.1.119_5555\\cases\\RT_2841\\ODF_NPI_RT2841\\picture\\22.py",
 			"D:\\SAT\\log.txt", 
 			"",
 			EMBEDDED);

+ 40 - 12
RunPython/RunPython/ScriptExecutor.cpp

@@ -107,18 +107,8 @@ DWORD __stdcall CScriptExecutor::_LogExportThread(LPVOID lpParam)
 	CloseHandle(that->m_hLogThread);
 	that->m_hLogThread = NULL;
 
-	// 关闭重定向句柄;
-	if (that->m_hStdErrorWrite)
-		CloseHandle(that->m_hStdErrorWrite);
-	that->m_hStdErrorWrite = NULL;
-
-	if (that->m_hStdOutWrite)
-		CloseHandle(that->m_hStdOutWrite);
-	that->m_hStdOutWrite = NULL;
-
-	if (that->m_hStdOutRead)
-		CloseHandle(that->m_hStdOutRead);
-	that->m_hStdOutRead = NULL;
+	// 结束重定向;
+	that->EndRedirectStdOut();
 
 	return 0;
 }
@@ -173,6 +163,9 @@ int CScriptExecutor::RedirectStdout(LPSTARTUPINFO si /*=NULL*/)
 		}
 		_close(wpfd);
 
+		// 备份进程原始标准输出;
+		m_hOldStdOutWrite = GetStdHandle(STD_OUTPUT_HANDLE);
+		// 设备进程标准输出,重定向到管道中;
 		if (!SetStdHandle(STD_OUTPUT_HANDLE, m_hStdOutWrite))
 		{
 			printf("Error:重定向失败\n");
@@ -535,6 +528,41 @@ BOOL CScriptExecutor::EndSubprocess()
 	return ret;
 }
 
+void CScriptExecutor::EndRedirectStdOut()
+{
+	// 关闭重定向句柄;
+	if (m_hStdErrorWrite)
+		CloseHandle(m_hStdErrorWrite);
+	m_hStdErrorWrite = NULL;
+
+	if (m_hStdOutWrite)
+	{
+		// 嵌入进程脚本;
+		if ( m_nRunType == EMBEDDED && m_hOldStdOutWrite)
+		{
+			// 恢复进程默认标准输出;
+			int fd = _open_osfhandle((intptr_t)m_hOldStdOutWrite, _O_TEXT);
+			if ( _dup2(fd, _fileno(stdout)) == 0)
+			{
+				_close(fd);
+				// 设置标准输出;
+				SetStdHandle(STD_OUTPUT_HANDLE, m_hOldStdOutWrite);
+				m_hOldStdOutWrite = NULL;
+			}
+			else
+			{
+				printf("Error:_dup2分配文件描述符失败\n");
+			}			
+		}
+		CloseHandle(m_hStdOutWrite);
+	}
+	m_hStdOutWrite = NULL;
+
+	if (m_hStdOutRead)
+		CloseHandle(m_hStdOutRead);
+	m_hStdOutRead = NULL;
+}
+
 void CScriptExecutor::InitScript(std::string strScript, std::string strLogPath, std::string strScriptCmd, int nRunType /*= PY_RUN_TYPE::EMBEDDED*/)
 {
 	// 判断脚本是否存在;

+ 3 - 0
RunPython/RunPython/ScriptExecutor.h

@@ -30,6 +30,7 @@ protected:
 	HANDLE			m_hStdOutRead;
 	HANDLE			m_hStdOutWrite;
 	HANDLE			m_hStdErrorWrite;
+	HANDLE			m_hOldStdOutWrite;					// 用于本进程标准输出备份;
 	// 子进程信息;
 	STARTUPINFO			m_si;
 	PROCESS_INFORMATION	m_pi;
@@ -61,6 +62,8 @@ protected:
 	BOOL EndSubprocess();
 	// 从管道读取日志;
 	void ReadFromPipe();
+	// 结束重定向句柄,恢复默认;
+	void EndRedirectStdOut();
 public:
 	// 初始脚本运行参数;
 	void InitScript(