简体   繁体   English

启动进程并在ruby脚本退出后使其保持运行

[英]Start a process and keep it running after the ruby script exits

I'm trying to write a ruby script that: 我正在尝试编写一个Ruby脚本:

  1. Run a command/script 运行命令/脚本
  2. Stores the command's process pid in a file so I can check if it's still running later, and 将命令的进程pid存储在文件中,以便稍后检查它是否仍在运行
  3. the command should keep running after the ruby code exits. 红宝石代码退出后,该命令应继续运行。

I'm successful in steps 1 and 2, but it looks like the started script (ie, the child process) terminates once the ruby code is finished. 我在第1步和第2步中都成功完成了,但是当ruby代码完成后,启动脚本(即子进程)看起来就终止了。

This is the last version of what I could think about (super simplified): 这是我能想到的最新版本(超级简化):

pid = fork do
  exec "/my/fancy/daemon/style/script"
end
File.open('tmp/process.pid', 'w') { |file| file.write(pid.to_s) }

Can you please tell me what am I doing wrong? 你能告诉我我在做什么错吗? The ultimate goal is to keep the other script (ie, the child process) running after the ruby code exits. 最终目标是在红宝石代码退出后保持其他脚本(即子进程)运行。

You can "detach" your child process: 您可以“分离”您的子进程:

Process.detach(pid)

See Process#detach for more info. 有关更多信息,请参见Process#detach

If you're running your script on a shell, and if your script is the last interactive process, your virtual terminal may exit and cause your child process to hangup as well. 如果您正在外壳程序上运行脚本,并且脚本是最后一个交互式进程,则虚拟终端可能会退出并导致子进程挂起。 If you consider not sending output to the terminal, you can use Process.daemon before running exec. 如果考虑不将输出发送到终端,则可以在运行exec之前使用Process.daemon。

See Process#daemon . 参见Process#daemon

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM