如何指示一个始终运行的命令进程停止从另一个命令进程停止?

时间:2016-01-01 05:34:29

标签: windows batch-file cmd

如何让一个命令进程向另一个命令进程发送命令?

嗯,特别是一个批处理脚本。我有一个启动服务,并在命令提示符窗口中每天24小时和每周7天运行它。

我需要的是一个批处理脚本,可以将命令“stop”发送到另一个命令进程。

我在网上查了一下,但没有什么特别的,并没有达到我的需要。

2 个答案:

答案 0 :(得分:1)

如果意图是停止其他命令提示符,为什么不直接杀死它呢?

Taskkill可以为您做到这一点。对于Eg:

Taskkill /PID 2704 /F

答案 1 :(得分:0)

或许可以使用文件作为几乎总是运行的命令进程的指示来终止自身。

几乎总是运行批处理文件AlwaysRunning.bat的示例代码:

@echo off

rem The example code in a nearly endless running loop just prints
rem a message and then waits 3 seconds to simulate process time
rem of other commands. Then the batch file checks if the file
rem used to signal a wanted exit of this batch file exists.
rem The file is deleted and command process exits in this case.

title %~n0

:Endless
echo %TIME% %~0 is running.
%SystemRoot%\System32\ping.exe 127.0.0.1 -n 4 >nul
if exist "%TEMP%\ExitAlwaysRunning.tmp" (
    rem Other commands to execute before exit.
    del "%TEMP%\ExitAlwaysRunning.tmp"
    exit
)
goto Endless

另一个批处理文件ExitRunning.bat的代码,用于在目录中发送文件ExitAlwaysRunning.tmp,以便批处理文件AlwaysRunning.bat尽快退出。

@echo off
rem Create in folder for temporary files an empty file as
rem indication for the always running batch task to exit.

copy NUL "%TEMP%\ExitAlwaysRunning.tmp" >nul

rem Define a maximum time of 10 seconds waiting for exit
rem of the other command process signaled by file just
rem created not existing anymore because deleted by the
rem nearly always running command process immediately
rem before exiting.

set "Timeout=10"

rem Check once per second if the other command process
rem deleted the temporary file immediately before exiting.

:WaitForExit
%SystemRoot%\System32\ping.exe 127.0.0.1 -n 2 >nul
if not exist "%TEMP%\ExitAlwaysRunning.tmp" (
    echo.
    echo AlwaysRunning.bat deleted file and exited.
    goto ProcessExited
)
set /A Timeout-=1
if not %Timeout% == 0 (
    echo %Timeout% sec remaining on waiting for exit.
    goto WaitForExit
)

del "%TEMP%\ExitAlwaysRunning.tmp"
echo.
echo Command process processing AlwaysRunning.bat is either
echo not running or ignored the indication by file to exit.

rem Command tasklist could be used to find out if the other batch file
rem is still running and then taskkill could be used to kill the other
rem command process when not exiting within specified time. But this
rem should not happen if the initial timeout value is set correct.

:ProcessExited
rem Put here your other commands executed after nearly
rem always running command process terminated itself.

echo.
pause

首先在命令提示符窗口中双击或运行AlwaysRunning.bat

然后在另一个命令提示符窗口中启动,或双击ExitRunning.bat