LoginSignup
53
50

More than 5 years have passed since last update.

bashスクリプトで子プロセスを全部殺すイディオム

Last updated at Posted at 2015-02-26

シェルスクリプトでバックグラウンドで子プロセスを動かしている場合、何も考えずに書くと元のプロセスを殺しても子プロセスが残ってしまいます。例えばこんな風に書くと:

#!/bin/bash

vmstat 1 > vmstat.log &
iostat 1 > iostat.log &

wait

Ctrl-C で止めても vmstat, iostat が残りっぱなしになります:

% ./stat.bash 
^C
% ps
  PID TTY          TIME CMD
 7951 pts/2    00:00:00 zsh
10423 pts/2    00:00:00 vmstat
10424 pts/2    00:00:00 iostat
10446 pts/2    00:00:00 ps

こんな時は EXIT を trap して jobs -p した結果を kill すればよいそうです:

#!/bin/bash
trap 'kill $(jobs -p)' EXIT

vmstat 1 > vmstat.log &
iostat 1 > iostat.log &

wait

こうしておけば Ctrl-C で子プロセスも一緒に止まってくれます:

% ./stat.bash 
^C

% ps
  PID TTY          TIME CMD
 7951 pts/2    00:00:00 zsh
10763 pts/2    00:00:00 ps

kill -9 した場合は残りますが、それはしかたないですね。

参考: http://stackoverflow.com/questions/360201/kill-background-process-when-shell-script-exit

備忘録として。

53
50
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
53
50