Browse Source

1、恢复进程默认标准输出失败,暂时未能解决;
2、子进程方式重定向,需要结束句柄;

scbc.sat2 5 years ago
parent
commit
1966c54991
2 changed files with 32 additions and 20 deletions
  1. 2 0
      RunPython/RunPython/RunPython.cpp
  2. 30 20
      RunPython/RunPython/ScriptExecutor.cpp

+ 2 - 0
RunPython/RunPython/RunPython.cpp

@@ -44,6 +44,8 @@ int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
 		Sleep(500);
 		while( !excutor.IsScriptOver() )
 			Sleep(100);
+
+		Sleep(15000);
 	}
 
 	system("pause");

+ 30 - 20
RunPython/RunPython/ScriptExecutor.cpp

@@ -15,6 +15,7 @@ CScriptExecutor::CScriptExecutor(void)
 	m_hStdOutRead = NULL;
 	m_hStdOutWrite = NULL;
 	m_hStdErrorWrite = NULL;
+	m_hOldStdOutWrite = NULL;
 
 	memset(m_szScriptPath, 0, MAX_PATH);
 	memset(m_szLogPath, 0, MAX_PATH);
@@ -530,37 +531,46 @@ BOOL CScriptExecutor::EndSubprocess()
 
 void CScriptExecutor::EndRedirectStdOut()
 {
+	OutputDebugString("Error:_dup2分配文件描述符失败\n");
+#if 0 // 恢复失败,代码有问题
+	// 恢复标准输出(嵌入进程脚本);
+	if ( m_nRunType == EMBEDDED && m_hOldStdOutWrite)
+	{
+		int fn = _fileno(stdout);
+		// 恢复进程默认标准输出;
+		int fd = _open_osfhandle((intptr_t)m_hOldStdOutWrite, _O_RDWR);
+		if ( _dup2(fd, _fileno(stdout)) == 0)
+		{
+			_close(fd);
+			// 设置标准输出;
+			SetStdHandle(STD_OUTPUT_HANDLE, m_hOldStdOutWrite);
+			m_hOldStdOutWrite = NULL;
+			// 设置标准流不使用缓冲,即时写入;
+			setvbuf(stdout, NULL, _IONBF, 0);
+		}
+		else
+		{
+			printf("Error:_dup2分配文件描述符失败\n");
+		}			
+	}
+#endif
+	printf("Error:_dup2分配文件描述符失败\n");
+
 	// 关闭重定向句柄;
 	if (m_hStdErrorWrite)
 		CloseHandle(m_hStdErrorWrite);
 	m_hStdErrorWrite = NULL;
 
-	if (m_hStdOutWrite)
+	// 只有子进程方式才关闭句柄;
+	if ( m_nRunType == SUBPROCESS && 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;
 	}
-	m_hStdOutWrite = NULL;
 
 	if (m_hStdOutRead)
 		CloseHandle(m_hStdOutRead);
-	m_hStdOutRead = NULL;
+	m_hStdOutRead = NULL;	
 }
 
 void CScriptExecutor::InitScript(std::string strScript, std::string strLogPath, std::string strScriptCmd, int nRunType /*= PY_RUN_TYPE::EMBEDDED*/)