Search code examples
windowsbatch-filecmdparallel-processingpipe

Calling several .exe-files in parallel from a Windows bat-file and piping the results to a common file?


I would like to have a standard Windows .bat-file calling 3 instances of an .exe-file in parallel and pipe the result to a common text-file. Pseudo-code:

SET PATH_TO_OUTPUT_FILE=%~dp0"All Devices Contents.txt"

echo Device on COM1 returned the following: >  %PATH_TO_OUTPUT_FILE%
start /b  ReadFromComPortDevice.exe  COM1   >> %PATH_TO_OUTPUT_FILE%
echo Device on COM2 returned the following: >> %PATH_TO_OUTPUT_FILE%
start /b  ReadFromComPortDevice.exe  COM2   >> %PATH_TO_OUTPUT_FILE%
echo Device on COM3 returned the following: >> %PATH_TO_OUTPUT_FILE%
start /b  ReadFromComPortDevice.exe  COM3   >> %PATH_TO_OUTPUT_FILE%

Obviously, the above will create file access errors because the file will already be used by the first process. Does anybody know a workaround?


Solution

  • the simplest approach would to be to redirect the output of the batch file as a whole to the specified file:

    @Echo off & CD /D "%~dp0"
    
    If not defined _ (
     Set _=_
     Prompt $_
     Start /B "" "%~f0" >"All Devices Contents.txt"
     (Prompt )
     Exit /B
    )
    
    echo Device on COM1 returned the following:
    start /b  ReadFromComPortDevice.exe  COM1
    echo Device on COM2 returned the following:
    start /b  ReadFromComPortDevice.exe  COM2
    echo Device on COM3 returned the following:
    start /b  ReadFromComPortDevice.exe  COM3
    
    Set "_="
    Goto :Eof