如何检查应用程序是否从批处理(好cmd)文件运行?

如果程序已经在运行,我不需要启动另一个实例。(我不能改变应用程序,使它只有单一实例。)

此外,应用程序可以作为任何用户运行。


当前回答

如果你有多个同名的。exe文件,你只想检查其中一个(例如,你关心的是C:\MyProject\bin\release\MyApplication.exe而不是C:\MyProject\bin\debug\MyApplication.exe),那么你可以使用以下方法:

@echo off

set "workdir=C:\MyProject\bin\release"
set "workdir=%workdir:\=\\%"

setlocal enableDelayedExpansion
for /f "usebackq tokens=* delims=" %%a in (`
    wmic process  where 'CommandLine like "%%!workdir!%%" and not CommandLine like "%%RuntimeBroker%%"'   get CommandLine^,ProcessId  /format:value
`) do (
    for /f "tokens=* delims=" %%G in ("%%a")  do (
        if "%%G" neq "" (
rem            echo %%G
            set "%%G"
rem            echo !ProcessId!
            goto :TheApplicationIsRunning
        )
    )
) 

echo The application is not running
exit /B

:TheApplicationIsRunning
echo The application is running
exit /B

其他回答

我不知道如何用内置CMD这样做,但如果你有grep,你可以尝试以下:

tasklist /FI "IMAGENAME eq myApp.exe" | grep myApp.exe
if ERRORLEVEL 1 echo "myApp is not running"

我通常在cmd提示符下执行以下命令来检查我的program.exe是否正在运行:

tasklist | grep program

如果你有多个同名的。exe文件,你只想检查其中一个(例如,你关心的是C:\MyProject\bin\release\MyApplication.exe而不是C:\MyProject\bin\debug\MyApplication.exe),那么你可以使用以下方法:

@echo off

set "workdir=C:\MyProject\bin\release"
set "workdir=%workdir:\=\\%"

setlocal enableDelayedExpansion
for /f "usebackq tokens=* delims=" %%a in (`
    wmic process  where 'CommandLine like "%%!workdir!%%" and not CommandLine like "%%RuntimeBroker%%"'   get CommandLine^,ProcessId  /format:value
`) do (
    for /f "tokens=* delims=" %%G in ("%%a")  do (
        if "%%G" neq "" (
rem            echo %%G
            set "%%G"
rem            echo !ProcessId!
            goto :TheApplicationIsRunning
        )
    )
) 

echo The application is not running
exit /B

:TheApplicationIsRunning
echo The application is running
exit /B

你应该检查父进程名,参见代码项目中关于基于。net解决方案的文章**。

一种非编程的检查方法:

发射用于cmd . exe 启动一个应用程序(例如,c:\windows\notepad.exe) 在进程资源管理器中检查“Notepad.exe”进程的属性 检查父进程(显示cmd.exe)

同样可以通过获取父进程名进行检查。

在Windows下,您可以使用Windows管理规范(WMI)来确保没有带有指定命令行的应用程序被启动,例如:

Wmic进程where (name="nmake.exe") get commandline | findstr /i /c:"/f load. exe"Mak“/c:”/f build。编译已经开始了!> %ALREADY_STARTED & exit /b 1)