child process owning the file used to redirect the std output of its parent process

萝らか妹 提交于 2019-12-23 05:23:18

问题


Scenario I have a batch file a.bat which below contains statements

A.exe >> a.txt
Test.exe >> a.txt

A.exe starts up another exe say b.exe (by _wpopen function) and returns. But after redirecting output of A.exe , ownership of a.txt seems to be transferred to b.exe. As test.exe cannot redirect its stdout to a.txt as b.exe is still running and still owns a.txt.

B.exe runs indefinitely, cannot wait for it to stop. And also I cannot redirect the output to multiple files. As these exe executions are a part of installation setup, so logging should be continuous and must be done to a single file

Is there any possible solution to this scenario? I want the file a.text to be free after a.exe returns!


回答1:


By putting the redirection on each line separately, you're requiring the command processor to reopen the file. If another process still has the original handle to the file open, as in your scenario, that won't work.

Instead, redirect the output once for multiple commands, or for the entire batch file. You can do this using the call command:

call :main >> a.txt
goto :eof

:main
A.exe
Test.exe
goto :eof

You could alternatively use brackets:

(
A.exe
Test.exe
) > test.txt

Or, if you only want some output to go to the file:

call :main 3>> a.txt
goto :eof

:main
A.exe >&3
Test.exe >&3
goto :eof

Keep in mind that until B.exe has exited, the log file will be held open, so the only way to write to it is to use an already existing handle. (This assumes that you cannot modify A.exe; if you can, that's probably a better solution.)

It might also be possible to avoid the problem altogether like this:

A.exe > temp.txt
type temp.txt >> a.txt


来源:https://stackoverflow.com/questions/22689393/child-process-owning-the-file-used-to-redirect-the-std-output-of-its-parent-proc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!