Returning a response with Ruby CGI before script i

2019-04-11 14:21发布

问题:

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


标签: ruby cgi