Skip to content

Instantly share code, notes, and snippets.

@ilmanzo
Created November 5, 2012 13:22
Show Gist options
  • Save ilmanzo/4017156 to your computer and use it in GitHub Desktop.
Save ilmanzo/4017156 to your computer and use it in GitHub Desktop.
a class to execute some command in background
class BackgroundJob
def initialize(cmd)
@pid = fork do
# this code is run in the child process
# you can do anything here, like changing current directory or reopening STDOUT
exec cmd
end
end
def stop!
# 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
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment