【问题标题】:How to start an .exe file using input/output file and set a time limit in batch?如何使用输入/输出文件启动 .exe 文件并批量设置时间限制?
【发布时间】:2013-12-10 15:24:14
【问题描述】:

在 windows 命令提示符下,当我想使用输入/输出文件运行程序时,我总是使用如下批处理命令:test.exe output.out。 (test.exe是程序名,input.it是输入文件名,output.out是输出文件名)

但是如果我使用这个命令,我不能为那个程序设置一个时间限制(即我不能强制程序在一段时间后退出)。 那么我应该使用什么命令来做到这一点?谢谢你帮助我。

【问题讨论】:

  • 你能在你的windows机器上安装额外的工具,比如cygwin吗? timeout 命令将优雅地解决您的问题。

标签: batch-file


【解决方案1】:

你可以使用taskkill命令:

start test.exe
ping 127.0.0.1 -n 5
taskkill /im test.exe /f 

在这里,它在 5 秒后被杀死。您可以指定任何持续时间(以秒为单位)。

【讨论】:

    【解决方案2】:
    start "" /b cmd /c "test.exe <input.in >output.out"
    timeout /t 10
    tasklist | find "test.exe" >nul && taskkill /f /im test.exe
    

    在没有附加到当前控制台的 cmd 实例中启动程序,等待 10 秒,如果程序仍在任务列表中,则将其杀死

    编辑 - 更新以处理 cmets 中指出的情况

    @echo off
        setlocal enableextensions
    
        start "" /b cmd /c "test.exe <input.in >output.out"
    
        call :timeoutProcess "test.exe" 10
        if errorlevel 1 (
            echo Program has been killed
        ) else (
            echo Program has ended in time
        )
    
        exit /b
    
    
    :timeoutProcess process timeout
        for /l %%t in (1 1 %~2) do (
            timeout.exe /t 1 >nul
            tasklist | find "%~1" >nul || exit /b 0
        )
        taskkill /f /im "%~1" >nul 
        exit /b 1
    

    【讨论】:

    • 另外一个问题:使用你的命令时,超时总是会持续10秒,但是程序可以提前结束。那么我可以在程序结束时立即终止超时过程吗?
    • @skyvn:更多的逻辑需要更多的代码。包含使用示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 2015-11-08
    相关资源
    最近更新 更多