2009年05月05日

任意のプロセスが起動しているか確認する方法 「$ ps cax | grep [command]」

livedoorClipに登録 | このエントリーをはてなブックマークに追加 | del.icio.usに登録 | MM/Memoに登録

/etc/logrotate.d/mysql-serverを見たら発見した


とあるサーバにてMySQLのログがローテートされてなかったのでDebianのlogrotate設定を参考にしてみた。
そこには見慣れないpsのオプションがあった。

$ cat /etc/logrotate.d/mysql-server
...(省略)...
                  if ps cax | grep -q mysqld; then
                    exit 1
                  fi
...(省略)...

「ps cax」?何だこれは。
axを指定する事はあっても、cを指定した事がなかった。

$ man ps
...(省略)...
       c               Show the true command name. This is derived from the
                       name of the executable file, rather than from the argv
                       value. Command arguments and any modifications to them
                       (see setproctitle(3)) are thus not shown. This option
                       effectively turns the args format keyword into the comm
                       format keyword; it is useful with the -f format option
                       and with the various BSD-style format options, which
                       all normally display the command arguments. See the -f
                       option, the format keyword args, and the format keyword
                       comm.
...(省略)...

実際にやってみよう。

cなし
$ ps ax | grep mysqld
 3033 ?        S      0:00 /bin/sh /usr/bin/mysqld_safe --skip-character-set-client-handshake
 3073 ?        Sl     0:50 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --user=mysql --pid-file=/var/run/mysqld/mysqld.pid --skip-external-locking --port=3306 --socket=/var/run/mysqld/mysqld.sock --skip-character-set-client-handshake
 3074 ?        S      0:00 logger -p daemon.err -t mysqld_safe -i -t mysqld
17052 pts/9    S+     0:00 grep mysqld
cあり
$ ps cax | grep mysqld
 3033 ?        S      0:00 mysqld_safe
 3073 ?        Sl     0:50 mysqld

なるほど。そう言う事か。
これは便利だ。


cを知らなかった頃


今まで無駄な事をやっていた事に気づかされる。

$ ps ax | grep mysqld | grep -v grep
  • 「grep mysqld」がpsの一覧に表れてしまう
  • grepコマンドを一覧から除外するために「grep -v grep」
$ ps ax | egrep '[m]ysqld'
  • psの一覧からgrepを除外したい
  • 「egrep '[m]ysqld'」と正規表現を書く事により、
    psの結果には「egrep '[m]ysqld'」が存在し、
    「egrep '[m]ysqld'」の条件にはマッチしなくなる
  • ※grepではなくegrep

いずれの方法でも欠点があった。
mysqldのプロセスとは関係のないプロセス、たとえばファイル名に「mysqld」が含まれるファイルを編集しているプロセスがあった場合にマッチしてしまう。

これをすっきり解決する方法が「cオプション」だった。




詳解 シェルスクリプト
アーノルド ロビンス ネルソン・H.F. ベーブ
オライリージャパン
売り上げランキング: 79971


トラックバックURL

この記事にコメントする

名前:
URL:
  情報を記憶: 評価: 顔