如何在不inheritancesubprocess中的句柄的情况下使用“start”命令?

这是一个说明我的问题的最小例子:

:: test.bat @echo off call test2.bat 2>&1 | findstr foo echo done calling test2 :: test2.bat @echo off start /B notepad >NUL echo done starting child process 

在这个示例中,findstr在记事本closures之前不会完成,大概是因为记事本已经从父级cmd进程inheritance了stdout。 如何修改test2.bat,使test.bat不会挂起?

我相信我可以说明没有任何批处理文件的问题。 在notepad.exe关闭之后,以下管道构造才会完成:

 start notepad | findstr "^" 

我预计记事本将在一个新的进程中执行,这个进程完全与cmd.exe管道分离,唯一的管道操作是START命令本身的输出(这是没有的)。 START命令返回“立即”,但只要记事本正在运行,管道就保持打开状态。

我不知道这是否是一个继承的I / O流,保持打开管道,但我可以证明记事本进程是以一种可能成为问题根源的方式继承流。 这与问题中出现的问题基本相同,即批量输出重定向 。

这是一个简单的批处理脚本: test.bat

 @echo off call :test >nul echo done calling test.bat exit /b :test start notepad 

请注意,当记事本开始时,stdout已被重定向到NUL,原因是call :test >nul重定向call :test >nul

现在看看当我从命令行发出一系列命令时会发生什么,从test.bat开始,将stdout重定向到一个文件:

 C:\test>test.bat >test.txt C:\test>REM The command returns immediately, and notepad remains open C:\test>type test.txt done calling test.bat C:\test>echo This fails as long as notepad remains open >test.txt The process cannot access the file because it is being used by another process. C:\test>type test.txt done calling test.bat C:\test>REM Now I close notepad C:\test>echo This works once notepad is closed >test.txt C:\test>type test.txt This works once notepad is closed C:\test> 

我仍然被这种行为所吹拂。 这似乎完全不合逻辑。

我不认为有任何方法来防止与cmd.exe流继承。

也许哈里·约翰斯顿的建议可以解决这个问题(从问题的评论): “我会写一个非常简单的可执行文件来禁用继承调用CreateProcess”。