Multithreading code in batch programs

Time:2021-11-14

The following content will be a simple example to use batch processing for multi process concurrency under windows to achieve the effect of “multithreading”.

For example, you need to Ping all IP addresses from 192.168.0.1 to 192.168.0.254, and output the result of whether you can ping to log.txt

The implementation is as follows:

REM main program. Bat only needs one line of code to call checkip.bat. After testing, cpu2.6g mem1g can be concurrent with about 40 processes

Copy codeThe code is as follows:
for /l %%i in (1,1,254) do (start /min cmd /c checkip.bat 192.168.0.%%i)

The contents of REM checkip.bat are as follows:

Copy codeThe code is as follows:
ping %1 -n 1
if %errorlevel%==0 (echo %1 alive>>log.txt) else (echo %1 dead>>log.txt)

According to the above information, I modified it myself and only need a main program to execute the code:
Program evolution

Copy codeThe code is as follows:
@echo off
if “%1″==”” (for /l %%a in (1,1,100) do (start /min cmd /c %0 10.120.6.%%a&ping 127.0.0.1 -n 1>nul))
if not “%1″==”” (ping -a %1 -n 1|find “reply” /i&&echo alive %1>>LogIP.txt||echo dead %1>>LogIP.txt)

In order to make the code too long and easy to read, I divided it into two lines. In fact, one line can be completed. You can modify the statements that run directly in the CMD window. If you can’t write them, you can ask me again.
Description of program knowledge points:

1. Judge whether the parameter is empty
2. When using the start command, please pay attention to the difference between goto and call
3. Use Ping to delay
4. Use the find command to determine whether the IP is powered on and record it in the log
5. The prompt information cannot be output.

Program re evolution
In order to empty the log file after each execution, the modification code is as follows:

Copy codeThe code is as follows:
@echo off
if “%1″==”” (
if exist “logip.txt” del LogIp.txt
for /l %%a in (1,1,100) do (start /min cmd /c %0 10.120.6.%%a&ping 127.0.0.1 -n 1 1>nul))
if not “%1″==”” (ping -a %1 -n 1|find “reply” /i&&echo alive %1>>LogIP.txt||echo dead %1>>LogIP.txt)

Of course, if you want to use two bat files, you can directly write two lines of code in two files, one line for each file.

explain:

1. At the end of the for statement, there is Ping 127.0.0.1 – N 1 1 > nul, – N 1 indicates pinging for 1 time, and the following 1 > nul indicates normal information redirection and forbidden output. For specific blog content, other article handles are redirected.
2. The statement if exist “logip. TXT” del logip.txt can be replaced by echo [% date%% time%] > logip.txt. The functions of these two sentences are the same. The specific use depends on your personal usage
The above are some of my own experience. I’m afraid I’ll forget it. Record it here.

Supplementary reference jack_ Meng