できない.dev

コマンドの実行にタイムアウトを設定するには

外部コマンドが終わらないときに、制限時間で止める書き方を各言語で示す。
タイムアウトの知らせ方が言語ごとに違う点と、Go で出力を受け取るとき制限時間を過ぎても待たされる点もまとめる。

公開:

選んだ言語は、ほかのサンプルコードを開いたときも最初に表示する。

Python

import subprocess
 
try:
    subprocess.run(["sleep", "5"], timeout=1)
except subprocess.TimeoutExpired as e:
    print("timed out after", e.timeout, "s")  # timed out after 1 s

subprocess.run の timeout に秒数を渡すと、その時間内に終わらないときコマンドを止めて TimeoutExpired を投げる。
例外の timeout 属性には渡した秒数が入る。

JavaScript

const { spawnSync } = require("node:child_process");
 
// timeout はミリ秒。超えるとコマンドが SIGTERM で止められる
const result = spawnSync("sleep", ["5"], { timeout: 1000 });
console.log(result.error.code); // ETIMEDOUT
console.log(result.signal); // SIGTERM
console.log(result.status); // null

spawnSync の timeout にはミリ秒を渡す。
超えるとコマンドが止められ、例外は投げずに error.code が ETIMEDOUT、signal が SIGTERM、status が null の結果が返る。

TypeScript

import { spawnSync } from "node:child_process";
 
// timeout はミリ秒。超えるとコマンドが SIGTERM で止められる
const result = spawnSync("sleep", ["5"], { timeout: 1000 });
const err = result.error as NodeJS.ErrnoException | undefined;
console.log(err?.code); // ETIMEDOUT
console.log(result.signal); // SIGTERM
console.log(result.status); // null

result.error の型は Error | undefined で code を持たないので、NodeJS.ErrnoException として読む。
status は number | null で、タイムアウトで止めたときは null になる。

Go

package main
 
import (
	"context"
	"errors"
	"fmt"
	"os/exec"
	"time"
)
 
func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
 
	// ctx の期限が来ると、実行中のコマンドが Kill される
	err := exec.CommandContext(ctx, "sleep", "5").Run()
	fmt.Println(err)                                            // signal: killed
	fmt.Println(errors.Is(ctx.Err(), context.DeadlineExceeded)) // true
}

exec.CommandContext に期限つきの context を渡すと、期限が来た時点でコマンドが Kill される。
Run が返すのは signal: killed というエラーなので、タイムアウトかどうかは ctx.Err() が context.DeadlineExceeded かで判断する。

Rust

use std::process::Command;
use std::thread::sleep;
use std::time::{Duration, Instant};
 
fn main() -> std::io::Result<()> {
    let mut child = Command::new("sleep").arg("5").spawn()?;
    let start = Instant::now();
 
    // 標準ライブラリにタイムアウト付きの待機は無いので、try_wait で見張る
    loop {
        if let Some(status) = child.try_wait()? {
            println!("finished: {}", status);
            break;
        }
        if start.elapsed() > Duration::from_secs(1) {
            child.kill()?;
            child.wait()?; // kill のあとも wait で回収する
            println!("timed out");
            break;
        }
        sleep(Duration::from_millis(50));
    }
    Ok(())
}

標準ライブラリにはタイムアウト付きの待機が無いので、try_wait で終了を見張り、制限時間を過ぎたら kill する。
kill は終了を待たないため、そのあとに wait を呼んで終わりを待つ。

Java

import java.util.concurrent.TimeUnit;
 
public class Main {
    public static void main(String[] args) throws Exception {
        Process p = new ProcessBuilder("sleep", "5").inheritIO().start();
 
        // waitFor に時間を渡すと、終わらなければ false が返る
        if (!p.waitFor(1, TimeUnit.SECONDS)) {
            p.destroyForcibly();
            p.waitFor();
            System.out.println("timed out"); // timed out
        }
    }
}

waitFor に時間と単位を渡すと、その時間内に終わらなければ false が返る。
止めるには自分で destroyForcibly を呼ぶ必要があり、waitFor のタイムアウトだけではコマンドは止まらない。

C#

using System.Diagnostics;
 
using var p = Process.Start("sleep", "5")!;
 
// WaitForExit にミリ秒を渡すと、終わらなければ false が返る
if (!p.WaitForExit(1000))
{
    p.Kill();
    p.WaitForExit();
    Console.WriteLine("timed out"); // timed out
}

WaitForExit にミリ秒を渡すと、その時間内に終わらなければ false が返る。
止めるには自分で Kill を呼ぶ必要があり、WaitForExit のタイムアウトだけではコマンドは止まらない。

タイムアウトの知らせ方は言語ごとに違う

sleep 5 を制限 1 秒で実行したとき、タイムアウトの知らせ方は次のように分かれた。

  • Python は TimeoutExpired を投げた。
  • Node.js の spawnSync は例外を投げず、結果の error.code が ETIMEDOUT になった。execFileSync は例外を投げ、その code が ETIMEDOUT で status は null だった。
  • Go は signal: killed というエラーを返した。
  • Rust・Java・C# は自分で時間を測るか、false を受け取って判断する。

Node.js で例外を投げない書き方を使うと、結果の error を見ない限りタイムアウトに気づけない。

Go で出力を受け取ると制限時間を過ぎても待たされる

sh -c "sleep 5; echo done" を Output で実行し、制限を 1 秒にして測った。

  • exec.CommandContext だけでは、エラーは signal: killed で返るものの、戻ってくるまで約 5 秒かかった。
  • cmd.WaitDelay に 500 ミリ秒を設定すると、約 1.5 秒で戻った。

止められたのは sh だけで、その子の sleep が標準出力のパイプを持ち続けていたため、出力の読み取りが終わるのを待っていたと考えられる。
シェル経由で孫のプロセスを起こすコマンドの出力を受け取るときは、WaitDelay を設定しておく。

時間切れを知らせるだけで、コマンドを止めない言語がある

Java の waitFor と C# の WaitForExit は、時間切れを false で知らせるだけでコマンドは止めない。
止めるには destroyForcibly や Kill を自分で呼ぶ。
Rust も kill を呼ぶのは自分である。

sh -c のようにシェルを挟むと、止められるのはシェルだけで、その先のコマンドは止まらないことがある。
前の節の Go の例がその一つである。
制限時間を付けたいコマンドは、できるだけシェルを挟まずに直接起動する。