How to run batch files in background while running multiple files in parallel

Viewed 404

I am writing a batch file which will execute 4 other batch files in parallel:

@echo off

echo %time%

(
    start call s1.bat
    start call s2.bat
    start call s3.bat
    start call s4.bat
) | set /P "="

echo %time%

But this is opening 4 new windows. Can anyone help, how to avoid opening multiple windows and run all those 4 batch files in background?

Adding /B is on of the option, but I don't to where to add it exactly.

(
    start /B call s1.bat
    start /B call s2.bat
    start /B call s3.bat
    start /B call s4.bat
) | set /P "="

Is giving me an error:

The process tried to write to a nonexistent pipe.

As I do not want to use VB or any other script, how to do it in batch?

1 Answers

This is a really interesting problem! It seems that there is some conflict with the redirection handles.

The main script awaits execution of the sub-scripts with the following code (on Windows 10):

(
    > nul start "" /B cmd /D /C call s1.bat
    > nul start "" /B cmd /D /C call s2.bat
    > nul start "" /B cmd /D /C call s3.bat
    > nul start "" /B cmd /D /C call s4.bat
) | set /P =""

The > nul redirection prevents any data to be written to the pipe |. It seems as soon as there becomes anything written to the standard output handle STDOUT (1), the main script does no longer wait (and sometimes the error message The process tried to write to a nonexistent pipe. arises, possibly depending on how fast the sub-script(s) execute(s)). However, as soon as the /B is removed, output to STDOUT by the sub-scripts does not affect the behaviour of the main script, which waits for all sub-scripts, and > nul is therefore no longer necessary.

The explicit cmd /C part is necessary because start would otherwise implicitly use cmd /K when starting internal commands like call which leave non-terminated processes cmd.exe behind upon completion of the respective sub-script.
The /D switch just prevents any auto-run commands to become executed.


When you use normal start without /B for running the sub-scripts, a new instance of the command interpreter is started, that is the process cmd.exe, and a new instance of the console window is started as a process conhost.exe.

Now using start /B still creates a new process cmd.exe but it uses the current process conhost.exe.

I do not know what exactly happens in the background and how all these processes interact, but it appears to me that the issue is connected to the lack of conhost.exe processes when using start /B. Maybe conhost.exe is establishing the redirection handles and hence the pipe. Anyway, as long as there is nothing written to the pipe, there is nothing to conflict, so set /P ="" waits for the related handle to become closed.

Related