微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在ruby中控制(启动/终止)后台进程(服务器应用程序)

我正在尝试通过 ruby为集成测试(实际规格)设置一个服务器,但无法弄清楚如何控制该过程.

所以,我想要做的是:

>为我的gem执行rake任务,执行集成规范
>任务需要首先启动服务器(我使用webrick),然后运行规范
>执行规范后,它应该杀死webrick所以我没有留下一些未使用的后台进程

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

希望有人能够提供帮助!

PS.我正在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以不同的方式创建进程.

原文地址:https://www.jb51.cc/ruby/270809.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐