【问题标题】:Set time out for a cmd execution为命令执行设置超时
【发布时间】:2013-12-28 10:00:43
【问题描述】:

我有一个 cmd 执行时间太长,我想为它设置一个超时时间。超时后,我可以去下一行执行。可能吗?我的cmd是这样的。

example1.exe /e:dosomething. 
example2.exe /e:dosomething.

我想给example1.exe设置超时,然后我可以去执行example2.exe 有什么方法吗?

【问题讨论】:

  • 谢谢,但这不是我想要的,执行example1.exe的时候,5分钟后才会结束执行,我想在执行完example1.exe之后再执行example2.exe 1 分钟后。
  • 我认为对你来说最好的方法是编写一个多线程 C++ 程序,其中一个线程运行命令,另一个等待在死线后杀死它,你可以编译程序并使用二进制文件作为命令。主要功能中的“argc”和“argv”获取命令示例1和2。如果您不理解我,请告诉我,我会提供更多帮助。
  • 你需要更加明确。 Example1 开始然后呢?稍等片刻,然后启动 example2?等待一段时间然后杀死example1并启动example2?如果 example1 终止或已经过去了一段时间,则启动 example2 - 终止 example1 吗?是否会有多个 example1 或 example2 实例同时运行?
  • 谢谢大家。特别感谢Behnma,你提醒我使用高级程序,我用C#启动了2个线程,它可以工作。非常感谢。

标签: cmd


【解决方案1】:

改编自之前的回答,以处理杀死或在超时时继续运行进程的情况

@echo off
    setlocal enableextensions

    rem Case 1 - Start example 1 and kill it after 60 seconds
    start "" /b example1.exe /e:dosomething
    call :timeoutProcess "example1.exe" 60

    rem Test why execution continues
    if errorlevel 1 (
        echo Program has been killed
    ) else (
        echo Program has ended in time
    )

    rem Case 2 - Start example1 and after 60 seconds continue,
    rem          leaving example1 running
    start "" /b example1.exe /e:dosomething
    call :timeoutProcess "example1.exe" 60 1

    rem Test why execution continues
    if errorlevel 1 (
        echo Timeout - Program keeps running
    ) else (
        echo Program has ended in time
    )

    exit /b

:timeoutProcess process timeout [leave]
    rem process = name of process to monitor
    rem timeout = timeout in seconds to wait for process to end
    rem leave   = 1 if process should not be killed
    for /l %%t in (1 1 %~2) do (
        timeout.exe /t 1 >nul
        tasklist | find "%~1" >nul || exit /b 0
    )
    if not "%~3"=="1" taskkill /f /im "%~1" >nul 
    exit /b 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 2016-01-04
    • 2012-05-17
    • 1970-01-01
    相关资源
    最近更新 更多