问题
Anyone know how to send a CGI response in Ruby before the CGI script is finished executing?
I'm creating a fire-and-forget HTTP API. I want a client to push data to me via HTTP and have the response return successfully, and then it swizzles the data and does some processing (without the client having to wait for a response).
I've tried several things that don't work, including fork. The following will just wait 5 seconds when invoked via HTTP.
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
cgi.out "text/plain" do
"1"
end
pid = fork
if pid
# parent
Process.detach pid
else
# child
sleep 5
end
回答1:
I answered my own question. Turns out I just need to close $stdin, $stdout, and $stderr in the child process:
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
cgi.out "text/plain" do
"1"
end
pid = fork
if pid
# parent
Process.detach pid
else
# child
$stdin.close
$stdout.close
$stderr.close
sleep 5
end
来源:https://stackoverflow.com/questions/4189230/returning-a-response-with-ruby-cgi-before-script-is-finished