怎么用脚本限制程序运行时间

wen 实用脚本 1

本文目录导读:

怎么用脚本限制程序运行时间

  1. Linux/Unix 系统
  2. Windows 系统
  3. 跨平台最佳实践
  4. Python 高级实现
  5. C/C++ 实现
  6. 高级功能:带日志输出
  7. 注意事项

我来介绍几种限制程序运行时间的方法,根据需求选择合适的方式:

Linux/Unix 系统

使用 timeout 命令(最简单)

# 限制命令运行10秒
timeout 10s ./your_program
# 限制命令运行1分钟
timeout 1m ./your_program
# 超时后发送SIGKILL强杀
timeout -k 5s 10s ./your_program
# 显示超时信息
timeout --preserve-status 10s ./your_program

使用 timelimit 命令

# 更复杂的限制,10秒警告,15秒强杀
timelimit -t 10 -T 15 ./your_program

使用 Python 脚本

import subprocess
import time
# 简单方式
try:
    subprocess.run(["your_program"], timeout=10)
except subprocess.TimeoutExpired:
    print("程序超时!")

Windows 系统

PowerShell 脚本

# 设置超时时间
$timeout = 10  # 秒
$process = Start-Process -FilePath "your_program.exe" -PassThru
# 等待进程结束
if (-not $process.WaitForExit($timeout * 1000)) {
    Write-Host "程序超时,正在终止..."
    $process.Kill()
} else {
    Write-Host "程序正常结束"
}

VBScript 方法

' 定时器实现
Set WshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
' 启动程序
Set objExec = WshShell.Exec("your_program.exe")
' 等待10秒
WScript.Sleep 10000
' 如果程序还在运行,则终止
If objExec.Status = 0 Then
    objExec.Terminate()
    WScript.Echo "程序超时,已终止"
End If

跨平台最佳实践

Bash 脚本(Linux/Mac)

#!/bin/bash
# 通用超时函数
run_with_timeout() {
    local timeout=$1
    local command=${@:2}
    # 后台运行命令
    "$@" &
    local pid=$!
    # 等待指定时间
    (sleep $timeout && kill -9 $pid 2>/dev/null) &
    local killer=$!
    # 等待程序完成
    wait $pid
    local status=$?
    # 取消定时器
    kill $killer 2>/dev/null
    if [ $status -ne 0 ] && [ $status -ne 143 ]; then
        echo "程序超时被终止"
        return 124
    fi
    return $status
}
# 使用示例
run_with_timeout 10 ./your_program

Python 高级实现

import signal
import subprocess
import threading
import os
class TimeoutProcess:
    def __init__(self, cmd, timeout):
        self.cmd = cmd
        self.timeout = timeout
        self.process = None
    def run(self):
        def timeout_handler():
            if self.process:
                self.process.kill()
                print(f"程序超时({self.timeout}秒),已终止")
        # 设置定时器
        timer = threading.Timer(self.timeout, timeout_handler)
        timer.start()
        try:
            self.process = subprocess.Popen(self.cmd, shell=True)
            self.process.wait()
        finally:
            timer.cancel()
# 使用示例
timeout_runner = TimeoutProcess("your_program", 10)
timeout_runner.run()

C/C++ 实现

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>
int main() {
    pid_t pid = fork();
    if (pid == 0) {
        // 子进程执行程序
        execl("./your_program", "your_program", NULL);
        exit(0);
    } else if (pid > 0) {
        // 父进程监控
        int timeout_seconds = 10;
        time_t start_time = time(NULL);
        while (1) {
            int status;
            pid_t result = waitpid(pid, &status, WNOHANG);
            if (result == pid) {
                printf("程序正常结束\n");
                break;
            }
            if (difftime(time(NULL), start_time) > timeout_seconds) {
                printf("程序超时,强制终止\n");
                kill(pid, SIGKILL);
                waitpid(pid, &status, 0);
                break;
            }
            sleep(1);
        }
    }
    return 0;
}

高级功能:带日志输出

#!/bin/bash
# 带日志的超时执行
run_with_timeout_and_log() {
    local timeout=$1
    local logfile=$2
    local command=${@:3}
    echo "[$(date)] 开始执行: $command (超时: ${timeout}s)" >> "$logfile"
    # 使用timeout命令并记录日志
    timeout "$timeout" "$@" >> "$logfile" 2>&1
    local exit_code=$?
    if [ $exit_code -eq 124 ]; then
        echo "[$(date)] 程序超时被终止" >> "$logfile"
    else
        echo "[$(date)] 程序结束,退出码: $exit_code" >> "$logfile"
    fi
    return $exit_code
}
# 使用
run_with_timeout_and_log 10 execution.log ./your_program

注意事项

  1. 信号处理:确保程序正确处理 SIGTERMSIGKILL 信号
  2. 资源清理:超时后要清理临时文件和进程资源
  3. 并发考虑:如果可能同时运行多个实例,使用进程ID避免混淆
  4. 错误处理:处理程序正常结束和超时两种情况

选择哪种方法取决于:

  • 操作系统环境
  • 对精确度的要求
  • 是否需要记录日志
  • 是否需要在超时前进行清理工作

抱歉,评论功能暂时关闭!