Skip to content

Instantly share code, notes, and snippets.

@sunny4381
Last active February 11, 2018 11:09
Show Gist options
  • Save sunny4381/c996e6a48b2eb4db833b to your computer and use it in GitHub Desktop.
Save sunny4381/c996e6a48b2eb4db833b to your computer and use it in GitHub Desktop.
Ruby で外部コマンドの非同期実行
# 外部プログラムを非同期実行する場合、以下の様な方法で実行する場合が多いと思います。
require "open3"
stdin, stdout, stderr = Open3.popen3(cmd)
# cmd の実行に時間がかかる場合、stdin, stdout, stderr が GC により閉じられる確率が高くなります。
# GC により閉じられた stderr に cmd が書き込むと EPIPE 例外が発生し、cmd が異常終了します。
# そこで、stdin, stdout, stderr が不要な場合は閉じておくほうがいいです。
require "open3"
Open3.popen3("#{cmd} > /dev/null 2>&1")
# 次のように spawn を直接使用してもいいです。
pid = spawn(cmd, in: "/dev/null", out: "/dev/null", err: "/dev/null")
Process.detach(pid)
# また、次のように、単に spawn を使用してもいいです。
pid = spawn(cmd)
Process.detach(pid)
# この場合、cmd は親プロセスの stdout と stderr を継承するので、
# cmd の出力は unicorn.stdout.log や unicorn.stderr.log に出力され(ると思い)ます。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment