Skip to content

Instantly share code, notes, and snippets.

@sandro
Created July 9, 2009 21:50
Show Gist options
  • Save sandro/144029 to your computer and use it in GitHub Desktop.
Save sandro/144029 to your computer and use it in GitHub Desktop.
fork a long running process
Spawn a long-running process in response to a POST request. The
request spawns a child and immediately redirects, making the request
non-blocking. The child changes the text on the index page from
"Running" to "Not running" after finishing its work.
Instructions:
ruby app.rb
visit http://localhost:4567
push "Run"
notice the text says "Running"
Refresh until the text says "Not running"
require 'rubygems'
require 'sinatra'
require 'haml'
module State
FILE_NAME = 'running'
def self.running?
File.exists? FILE_NAME
end
def self.reset!
File.unlink FILE_NAME
end
def self.run!
system 'touch', FILE_NAME
end
end
get '/' do
@running = State.running?
haml :index
end
get '/reset' do
State.reset!
redirect '/'
end
post '/' do
State.run!
pid = fork { sleep 2; State.reset! }
Process.detach pid
redirect '/'
end
- if @running
Running
- else
Not running
%form{:action => "", :method => "post"}
%button{:type => "submit"} Run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment