Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a response with Ruby CGI before script is finished?

Tags:

ruby

cgi

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
like image 659
Luke Ehresman Avatar asked Aug 22 '26 02:08

Luke Ehresman


1 Answers

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
like image 80
Luke Ehresman Avatar answered Aug 23 '26 18:08

Luke Ehresman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!