LoginSignup
5
3

More than 5 years have passed since last update.

Capistranoでリモートサーバ上でバックグラウンドプロセスを実行する

Last updated at Posted at 2015-10-16

Capistrano v3対応で、やり方を調べたのでメモ。
通常のコマンドと同様に実行すると、Capistrano自体が終わらなくなってしまうので特殊な方法をとる必要がありました。

Starting background tasks with Capistrano

に投稿されてましたが

execute "nohup CMD > /dev/null 2>&1 &"

としないといけないようです。
単純にアンパサンド(&)をつけても影響しないので
nohup でプロセスを実行して、標準(エラー)出力を破棄しないといけないようですね。

で、実行したやつをCapistranoから終了する方法を書いてみたのでついでにメモっておく。

kill
namespace :task do
  task :start do
    # abbrev
  end

  task :finish do
    on roles(:role) do
      # pgrep -a じゃないと取れない環境もある
      res = capture "pgrep -f CMD -l |grep '..(abbrev)..' |grep #{current_path}"

      pid_list = []
      res.split("\n").each do |row|
        # capistranoで実行したpgrepコマンドがbashとかで実行されてるので無視
        pid = row.split[0]
        unless row.include?("bash")
          pid_list.push(pid)
        end
      end

      unless pid_list.empty?
        pid_list.each do |pid|
          execute "kill -9 #{pid}"
        end
      end
    end
  end
end
5
3
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
5
3