Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you fork in Windows batch file?

Tags:

batch-file

cmd

I want to start two programs from the batch file, (also batch files) - they will execute few seconds. Then in the main batch file I want to wait while both are finished and then continue main execution. Is that possible at all?

like image 315
exebook Avatar asked Dec 20 '13 07:12

exebook


People also ask

Can you edit a batch file while it running?

But the extra code slows things down, so it's not worth doing unless the code is dependent on blank lines. Save this answer. Show activity on this post. Short answer: yes, batch files can modify themselves whilst running.

Can a batch file run a Shortcut?

If you want to use a custom file icon for your batch file, we recommend using a shortcut. Right-click the desktop and select New > Shortcut. Choose a location, ideally the same as your batch file, and click Next. Then enter a name for the shortcut and click Finish.

Can a batch file take arguments?

Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on.

Can Windows batch file run on Linux?

No. The bat files are windows shell scripts, which probably execute windows commands and expect to run in a windows environment. You need to convert them to shell scripts in order to run them on linux, as your bash shell can not understand dos commands.


1 Answers

You can, sort of:

@echo off
set Token=MAIN_%RANDOM%_%CD%
start "%Token%_1" cmd /c child1.cmd
start "%Token%_2" cmd /c child2.cmd
:loop
ping -n 2 localhost >nul 2>nul
tasklist /fi "WINDOWTITLE eq %Token%_1" | findstr "cmd" >nul 2>nul && set Child1=1 || set Child1=
tasklist /fi "WINDOWTITLE eq %Token%_2" | findstr "cmd" >nul 2>nul && set Child2=1 || set Child2=
if not defined Child1 if not defined Child2 goto endloop
goto loop
:endloop
echo Both children died.

child1 and child2 were just executing pause. This uses a more or less unique token to identify the child batch files. They are started in an own window with start and each one is given a specific window title. Using that window title we can find them again using tasklist and determine whether they are still running.

It gets a little tricky figuring out whether the batch files are still running. tasklist with the window title filter does what it's supposed to do, but it won't return a sensible errorlevel. That's why we have to pipe through findstr to pick up the process name (to avoid being language-sensitive by picking up the error message).

like image 72
Joey Avatar answered Oct 17 '22 06:10

Joey