Rake task for running a server in an independent thread then killing the thread when the task is complete?

StackOverflow https://stackoverflow.com/questions/10454699

  •  05-06-2021
  •  | 
  •  

Pregunta

How do I launch a thread within a rake task then kill the tread when the task is complete.

Essentially I am writing a rake task to test a jekyll site. I would like be able to launch the server, do some other tasks and then destroy the thread when the task is complete. Here is what I have thus far:

task :test_site do
  `ejekyll --server`
  `git -Xdn`
  if agree( "Clean all ignored files?")
    git -Xdf
  end
end

but unfortunately the only way I know of to stop the jekyll --server is to use ctrl c. I would be happy to hear of a way to stop a jekyll --server in a manor which does not exit the rake task but please just comment as the question is specifically asking about threading and rake tasks.

¿Fue útil?

Solución

You want Process.spawn, not a thread. It's a new process, not a thread of execution within an existing process. You get the PID back, so just send Process.kill(:QUIT, pid) or whatever method you want to use to kill the spawned processed.

pid = Process.spawn(
  "ejekyll", "--server",
  out: "/dev/null",
  err: "/dev/null"
)

# you may need to add a short sleep() here

# other stuff

Process.kill(:QUIT, pid) && Process.wait

If ejekyll has a command line option to run in the foreground, it would be better to use that, otherwise if it self-daemonizes you need to know where it stores its PID file, in order to identify and kill the daemon.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top