简体   繁体   English

如何检查批处理文件是否运行并避免双重执行?

[英]How to check if a batch file runs and avoid a dual execute?

I want to make a batch script but i want to avoid a dual execution. 我想制作一个批处理脚本,但我想避免双重执行。 So i have tried to check if it's running. 所以我试图检查它是否正在运行。

I used the following method but i am taking this message ERROR: The process "MyBatchTool" not found 我使用了以下方法,但我ERROR: The process "MyBatchTool" not foundERROR: The process "MyBatchTool" not found消息ERROR: The process "MyBatchTool" not found

echo off
TITLE MyBatchTool
SETLOCAL ENABLEDELAYEDEXPANSION
tasklist /fi "imagename eq MyBatchTool" |find ":" > nul
if errorlevel 1 echo "Is Running"
pause

Do you have a suggestion ? 你有什么建议吗 ?

echo off
TITLE MyBatchTool
SETLOCAL ENABLEDELAYEDEXPANSION
tasklist /fi "imagename eq MyBatchTool" 2>nul |find ":" > nul 2>nul && (
   echo "Is not Running"
   color
)||(
    echo "Is running"

)
pause

You could use a file lock, the lock will be removed when the batch file exits even when an error occurs. 您可以使用文件锁,即使出现错误,批处理文件退出时,该锁也会被删除。
And it's safe that only one process can hold the lock. 而且只有一个进程可以持有该锁,这是安全的。

2> nul (
    9> lock.tmp 2>&1 (
    call :main
    ) || ( echo Is still runiing )
)
exit /b

:main
echo This will only run in one instance
ping -n 10 localhost

The first part is for creating an exclusive lock file. 第一部分是用于创建排他锁文件。 The 2>nul supresses the error message when you try to start the batch a second time while it's running. 当您尝试再次运行批处理时, 2>nul阻止错误消息。

For more examples and descriptions you could search for dbenham's posts to this topic at SO or dostips.com 有关更多示例和描述,您可以在SO或dostips.com上搜索dbenham关于该主题的帖子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM