用bat批处理启动、关闭控制台程序

调用方要求把windows下几个互相调用的web服务封装为exe形式。为了方便调用方使用,要求提供启动和关闭bat脚本。

启动脚本start.bat

@echo off
set port_backend=5000
start "ne_backend" cmd /k call start_backend.bat
echo 等待后端启动完成...
:start
for /f "tokens=3 delims=: " %%a in ('netstat -an') do (
if "%%a"=="%port_backend%" goto end
)
goto start

:end
echo 启动前端...
start "ne_frontend" cmd /k call start_frontend.bat
exit

总脚本负责维护启动顺序和端口。

一共启动2个exe,一个backeend 一个frontend 位置不同。

通过等待端口,判断backen启动完成,用goto语句 跳出循环,然后再启动下一个frontend

所以单独写两个各自的启动脚本start_backend.bat  start_frontend.bat

用start  新启动每个窗口。start的第一个参数 规定了启动后控制台的窗口 title文字。用于关闭时根据这个关闭。 这样避免了具体exe的名字

最后是exit 全部启动完毕后,这个start.bat总脚本就退出了,只剩2个独立的控制台在运行。

具体启动脚本大同小异,主要是切换当前工作路径(current work Directory),直接启动exe程序,也不退出。

start_backend.bat

@echo off
%~d0
cd %~dp0
cd "./backend"
app

start_frontend.bat

@echo off
%~d0
cd %~dp0
frontend

关闭脚本end.bat

@echo off
taskkill /fi "WindowTitle eq ne_frontend*"
taskkill /fi "WindowTitle eq ne_backend*"

因为实际窗口名是这样的:

但是我懒得抄后面啰嗦的语句了,而且有空格 也不知道怎么嵌套进 

"WindowTitle eq ne_frontend*"  

这样的双引号语句里。所以干脆用*模糊匹配了。

但是  万一系统里其他运行的exe(或者启动了我们的exe之后,又启动了别的exe),恰好别的exe的窗口title和我们这俩前缀重名,运行end.bat 就可能关闭错了。

为了防止这个问题,在start.bat脚本里 对每个窗口名都加了自定义前缀"ne_" 也可以加别的,更复杂点,保证没别的程序会这样。

有点类似C++用#if define 防止重复include 头文件

原文地址:https://www.cnblogs.com/xuanmanstein/p/12964375.html