加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

windows – 如何在不继承子进程中的句柄的情况下使用“start”命

发布时间:2020-12-14 02:51:18 所属栏目:Windows 来源:网络整理
导读:这是一个说明我问题的最小例子: :: test.bat@echo offcall test2.bat 21 | findstr fooecho done calling test2:: test2.bat@echo offstart /B notepad NULecho done starting child process 在此示例中,在记事本关闭之前,findstr将无法完成,可能是因为记事
这是一个说明我问题的最小例子:

:: 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将无法完成,可能是因为记事本已从父cmd进程继承了stdout.如何修改test2.bat以便test.bat不挂起?

解决方法

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

start notepad | findstr "^"

我希望记事本将在一个完全与cmd.exe管道解除关联的新进程中执行,并且唯一被管道传输的是START命令本身的输出(没有). START命令“立即”返回,但只要记事本正在运行,管道就会保持打开状态.

我不知道它是否是一个保持管道打开的继承I / O流,但我可以证明记事本进程是以可能是问题根源的方式继承流.这基本上与Issue with output redirection in batch提出的问题相同.

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

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

:test
start notepad

请注意,由于call:test> nul的重定向,当记事本启动时stdout已被重定向到NUL.

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

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的流继承.

也许Harry Johnston的建议可以解决问题(来自问题评论):“我写了一个非常简单的可执行文件来调用CreateProcess并禁用继承.”

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读