单实例批处理文件? [英] Single instance batch file?

查看:216
本文介绍了单实例批处理文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

:: dostuff.bat
@echo off
:: insert long-running process call here
: End

我可以添加到这个批处理文件是什么让它终止,如果当它执行它已经在另一个进程中运行?

What can I add to this batch file to make it terminate if it's already running in another process when it's executed?

推荐答案

哦,如果有可能是有史以来唯一只有一个实例,那么你也许可以用地方创建一个虚拟文件,可能是在临时目录中执行此操作:

Well, if there can be only exactly one instance ever, then you can probably do this by creating a dummy file somewhere, probably in the temp directory:

copy NUL "%TEMP%\dostuff_is_doing_stuff.tmp"

您然后删除它,你就大功告成了之后:

you then remove it after you're done:

del "%TEMP%\dostuff_is_doing_stuff.tmp"

和在批处理文件的开始,你可以检查文件是否存在,并相应地退出:

and at the start of the batch file you can check whether that file exists and exit accordingly:

if exist "%TEMP%\dostuff_is_doing_stuff.tmp" (
    echo DoStuff is already running. Exiting ...
    exit /b 1
)

同样的,你可以做到这一点通过改变窗口的标题,这也应该是对更强大的一个<大骨节病>控制 + <大骨节病> C 'ED或崩溃批处理文件。

Similarly, you can do that by changing the window title, which should also be more robust against a Ctrl+C'ed or crashed batch file.

设置标题:

title DoStuff

重新设置它算账:

Re-set it afterwards:

title Not doing stuff

检查吧:

tasklist /FI "WINDOWTITLE eq DoStuff"

但是,这有一个问题:在CMD以管理员身份运行,你会得到管理员:DoStuff作为标题。不与任务列表不再匹配。也通过检查你能砍,解决它。管理员:DoStuff,但可能会因Windows用户界面语言神态各异,所以它可能不是最好的解决办法

However, this has one problem: When cmd runs as administrator you'll get "Administrator: DoStuff" as the title. Which doesn't match anymore with tasklist. You can hack-solve it by also checking for "Administrator: DoStuff" but that might look different depending on the Windows UI language, so it's probably not the best solution.

这篇关于单实例批处理文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆