我正在尝试通过 ruby 为集成测试(实际上是规范)设置一个服务器,但不知道如何控制该过程。
所以,我要做的是:
- 为我的 gem 运行一个执行集成规范的 rake 任务
- 任务需要先启动服务器(我使用 webrick),然后运行规范
- 执行规范后,它应该会杀死 webrick,这样我就不会留下一些未使用的后台进程
webrick 不是必需的,但它包含在 ruby 标准库中,因此能够使用它会很棒。
希望有人能提供帮助!
附言。我在 linux 上运行,所以让这个适用于 windows 的工作不是我的主要优先事项(现在)。
最佳答案
标准方法是使用系统函数 fork(复制当前进程)、exec(用可执行文件替换当前进程)和 kill(向进程发送信号以终止它)。
例如:
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 以不同的方式创建进程。
关于ruby - 如何在 ruby 中控制(启动/终止)后台进程(服务器应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1993071/