编写一个简单的批处理文件来检查程序是否 运行

Writing a simple batch file that checks if a program is running

我和我的几个朋友正在使用 Dropbox 上的共享文件夹,我们的 minecraft 服务器已上传到该文件夹​​。这一点是任何人都可以随时启动服务器,而不是一个人必须一直 运行 它。

唯一的问题是,两个人可能同时启动服务器,并且可能会出现重叠的保存文件。为了解决这个问题,我想写一个简单的批处理文件。

逻辑是这样的:

  1. 如果进程 "minecraft_server.1.8.1" 是 运行ning,将服务器文件夹重命名为 "RUNNING AS _INSERT_NAME_HERE_",否则将其重命名回 "Minecraft server"

  2. NAME 将被读取为计算机名称(如果可能的话),或者从用户创建的某个 txt 文件(写入他们自己的名字)

我从来没有写过批处理文件,我不知道这是否可行,但它看起来很简单,我们将不胜感激。

提前致谢。

好的,经过一些修改,我写了我的第一个批处理文件。在大多数情况下它似乎在工作,但我似乎无法实现正确的循环。

@echo off
IF EXIST *_RUNNING.txt (
echo "ERROR, SERVER ALREADY RUNNING as %computername%"
pause
EXIT
) ELSE (
copy NUL %computername%_RUNNING.txt 
START /WAIT minecraft_server.1.8.1.exe
tasklist /FI "IMAGENAME eq javaw.exe" 2>NUL | find /I /N "javaw.exe">NUL
:loop 
IF "%ERRORLEVEL%"=="0" (
TIMEOUT /t 5
GOTO loop
) ELSE (
del %computername%_RUNNING.txt
echo "Server ended."
pause
EXIT ) )

当我启动 minecraft_server.1.8.1.exe 时,它会启动 javaw.exe,这就是启动服务器的实际进程。之后,我只是检查进程是否仍在 运行ning 中。但是我似乎无法循环代码的特定部分,我不断收到 synatx 错误。

这不是您在问题主题中要查找的内容,但如果我没弄错的话,您希望避免服务器启动两次。所以我会做以下事情:

创建一个批处理文件:

首先检查是否存在名为 *_MinecraftServer.txt 的文件。如果是,它假定服务器已经 运行ning 并且简单地退出。 如果不存在这样的文件,它会创建该文件。 然后它启动服务器。 服务器退出后,文件将被删除。

这将是这样的:

@echo off
REM Define a filename for the text-file informing other people that a server is running
SET FILENAME=%computername%_MinecraftServer.txt
REM Check if such a file already exists, if not refuse to start:
if exist *_MinecraftServer.txt (
  REM Such a file exists, print the content of the file:
  echo "ERROR, SERVER ALREADY RUNNING"
  type *_MinecraftServer.txt
) else (
  REM No such file is found. Create a file, then start the server process.
  echo "SERVER is running on %computername%" > %FILENAME%
  REM replace the notepad.exe with the name of the server.exe (and all    params it requires)
  REM Maybe you will also need to write the full-path to the server
  notepad.exe
  REM Once the server exits, remove the file
  del %FILENAME%
  echo "Server exited"
)
REM Require the user to hit a key before exiting the batch:
pause

此示例批处理启动了一个 notepad.exe 并创建了一个文件 COMPUTERNAME_MinecraftServer.txt。 您必须将 notepad.exe 替换为 minecraft 服务器 exe 的路径。 请注意,如果涉及的任何目录包含空格,我不确定此批处理是否有效。

当然,这只有在所有人从现在开始只使用批处理文件启动服务器时才有效。 此外,理论上多个服务器可以是 运行 如果多个用户或多或少同时启动服务器,因为在 dropbox 上传和分发创建的 txt 文件之前会有一些延迟。