1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【小ネタ】一定時間応答が返らないコマンドを強制終了するコマンド(timeout)

Last updated at Posted at 2020-02-17

はじめに

今日はちょっとした小ネタ。

別件で調べものをしていた際にスクリプトなどで「一定時間コマンドが返って来なかった場合」的なロジックを組み込む時に使えそうなコマンドを見つけたので、備忘がてら紹介します。
自分はwhileで回しながらsleepをかけたり、みたいなことをしていたのですが、今時のLinuxはそんなことしなくても良さそうですよ、という話です。

timeoutコマンドとは

timeoutコマンドは、指定したコマンドの実行時間を指定し、その間に終われば正常終了、終わらなければ異常終了(打ち切り)とするものです。

  • 書式 : timeout (num) (command)

詳細なオプションなどは下記の記事(@IT)を参照。

※タイムアウトの単位を秒(デフォルト)以外に分や時間で指定したり、終了時のシグナルを指定したり等、割とかゆいところに手が届く仕様になっているようです。

試してみました

### 正常時 ###
$ time timeout 3 sleep 2 ; echo $?

real    0m2.002s
user    0m0.002s
sys     0m0.000s
0

  →時間内に終わった場合はRC=0が返ります

### 異常時 ###
$ time timeout 3 sleep 6 ; echo $?

real    0m3.001s
user    0m0.002s
sys     0m0.000s
124

  →指定した時間に到達した時点でコマンドは強制終了(RC=124)となります
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?