【问题标题】:Process.spawn child does not receive TERMProcess.spawn 孩子没有收到 TERM
【发布时间】:2014-03-03 20:04:42
【问题描述】:

我正在尝试以编程方式生成一个 Puma 进程,然后通过发送 TERM 来终止它。

为此,我使用了Process.spawn,它返回一个pid。这个 PID 不是 puma 进程的 PID,而是产生 puma 的 shell 命令的 PID

pid = Process.spawn "bundle exec puma test/fixtures/app.ru -w 3 -t 1:1 -p 0 -e development > test/logs/puma_1961_1393875906.917352.log"
=> 10711

现在我可以运行ps aux | grep puma,我可以看到它正在运行

schneems        10719   0.0  0.1  2488912   7564 s000  S+    1:57PM   0:00.02 puma: cluster worker: 10712
schneems        10718   0.0  0.1  2488912   7524 s000  S+    1:57PM   0:00.02 puma: cluster worker: 10712
schneems        10717   0.0  0.1  2489936   7652 s000  S+    1:57PM   0:00.02 puma: cluster worker: 10712
schneems        10712   0.0  0.3  2478612  24596 s000  S+    1:57PM   0:00.47 ruby /Users/schneems/.gem/ruby/2.1.1/bin/puma test/fixtures/app.ru -w 3 -t 1:1 -p 0 -e development

但是您会注意到,正如我之前提到的,返回的 PID 10711 并未列出。它实际上是一个(sh)进程

$ ps -p 10711
  PID TTY           TIME CMD
10711 ttys000    0:00.00 (sh)

现在回到红宝石之地。当我尝试通过Process.kill('TERM', pid) 终止 puma 时,shell 进程已终止,但 puma 继续在后台运行。 Puma 从来没有收到过SIGTERM

puts pid
10711
Process.kill("TERM", pid)
=> 1
Process.wait(pid)

还有其他方法可以从 Ruby 内部持续生成并杀死美洲狮吗?为什么产生的进程没有向它的孩子(美洲狮)发送信号的任何线索。这是我的操作系统、Ruby 或 Puma 中的错误吗?也许这是预期的行为?

这是我的app.ruhttps://gist.github.com/schneems/18c216cc159772c80361

【问题讨论】:

  • 看起来诀窍是在我的命令 `Process.spawn("exec ") 之前添加“exec”
  • 也不使用>重定向标准输出做同样的事情

标签: ruby bash shell process


【解决方案1】:

最快的破解方法是使用exec

# Bad quick fix
pid = Process.spawn "exec bundle exec puma test/fixtures/app.ru -w 3 -t 1:1 -p 0 -e development > test/logs/puma_1961_1393875906.917352.log"

这会用调用的进程替换 shell。

但是,您永远不应该将 Process.spawn 与 shell 命令一起使用。当与变量结合时,它会导致令人惊讶、不安全和不可预测的行为。相反,您应该分开参数并自己设置重定向:

# Good solution
pid = Process.spawn("bundle", "exec", "puma", "test/fixtures/app.ru", "-w", "3", "-t", "1:1", "-p", "0", "-e", "development", :out=>"test/logs/puma_1961_1393875906.917352.log")

这首先避免了shell。

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 2017-11-11
    相关资源
    最近更新 更多