LoginSignup
49
46

More than 5 years have passed since last update.

pgrep/pkillを使おう

Last updated at Posted at 2015-10-07

前提

OS X (El capitan)

pgrep

よく起動中のプロセスを検索したくて

$ ps aux | grep foo

とかやっちゃうのですが、これをやると、

$ ps aux | grep vagrant
uraura          1916   0.0  0.0  2464336   3328 s001  S+    8:51AM   0:02.69 ssh vagrant@127.0.0.1 -p 2222 -o Compression=yes -o DSAAuthentication=yes -o LogLevel=FATAL -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -i /Users/uraura/.ssh/private_key
uraura          1915   0.0  0.0 145164392   1452 s001  S+    8:51AM   0:00.04 vagrant ssh
uraura          8225   0.0  0.0  2434836    640 s002  R+   11:54AM   0:00.00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn vagrant

とかいう感じで、目的のものも見れるけど、余分なgrepのプロセスまで載ってきたりするんですね。
grepにエイリアスが設定されてるともう目もあてられない感じ。

$ ps aux | grep vagrant | grep -v grep

なんてちょっとイケてないしメンドいですね。というわけで

プロセスID、プロセス名と引数全部を取得
$ pgrep -fl vagrant

1915 vagrant ssh
1916 ssh vagrant@127.0.0.1 -p 2222 -o Compression=yes -o DSAAuthentication=yes -o LogLevel=FATAL -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -i /Users/uraura/.ssh/private_key

で、だいたいps〜grep〜相当のものが取れます。

また、

起動時の引数まで全部を対象に検索して、プロセスIDだけ取得
$ pgrep -f vagrant

1915
1916

であればプロセスIDだけ取得できるので、プロセスを対象に何かしたい場合は使えるかもしれません。

pkill

pgreppkillはセットになっていて、ほぼ同じオプションが使えます。
なので、pgrepで対象のプロセスを確認しpkillでぶっ殺す、という使い方になると思います。

# 確認
$ pgrep -f vagrant
# 始末
$ pkill -f vagrant

# シグナルを指定
$ pkill -SIGKILL -f vagrant

おまけ

CentOS 7にしたらpgrepコマンドの仕様が変わっていた - Qiita 細かいオプションはOS等により変わるようなのでmanを読みましょう。

49
46
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
49
46