如何在 ruby​​ 中控制(启动/终止)后台进程(服务器应用程序) [英] how to controller (start/kill) a background process (server app) in ruby

查看:64
本文介绍了如何在 ruby​​ 中控制(启动/终止)后台进程(服务器应用程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 ruby​​ 为集成测试(实际上是规范)设置服务器,但不知道如何控制该过程.

i'm trying to set up a server for integration tests (specs actually) via ruby and can't figure out how to control the process.

所以,我想做的是:

  1. 为我的 gem 运行一个执行集成规范的 rake 任务
  2. 任务需要首先启动服务器(我使用 webrick)然后运行规范
  3. 执行规范后,它应该杀死 webrick,这样我就不会留下一些未使用的后台进程

webrick 不是必需的,但它包含在 ruby​​ 标准库中,因此能够使用它会很棒.

webrick is not a requirement, but it's included in the ruby standard library so being able to use it would be great.

希望有人能帮忙!

ps.我在 linux 上运行,所以在 Windows 上进行这项工作不是我的主要优先事项(现在).

ps. i'm running on linux, so having this work for windows is not my main priority (right now).

推荐答案

标准方法是使用系统函数 fork(复制当前进程)、exec(用可执行文件替换当前进程)和 kill(向进程发送信号以终止它).

The standard way is to use the system functions fork (to duplicate the current process), exec (to replace the current process by an executable file), and kill (to send a signal to a process to terminate it).

例如:

pid = fork do
  # this code is run in the child process
  # you can do anything here, like changing current directory or reopening STDOUT
  exec "/path/to/executable"
end

# this code is run in the parent process
# do your stuffs

# kill it (other signals than TERM may be used, depending on the program you want
# to kill. The signal KILL will always work but the process won't be allowed
# to cleanup anything)
Process.kill "TERM", pid

# you have to wait for its termination, otherwise it will become a zombie process
# (or you can use Process.detach)
Process.wait pid

这应该适用于任何类 Unix 系统.Windows 以不同的方式创建进程.

This should work on any Unix like system. Windows creates process in a different way.

这篇关于如何在 ruby​​ 中控制(启动/终止)后台进程(服务器应用程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆