0

I have this simple sinatra web app:

require 'sinatra'

get '/' do
    "Success."
end

get '/app' do
    "done"
    response["Connection"] = "Close"
    `sudo pkill blink` 
    `gpio write 0 0` 
    `sudo ./blink #{params["func"]}`
end

./blink is a program that runs forever and does not terminate, so when I access http://127.0.0.1/app?func=2 in a browser, I just get a loading loop and "done" is not shown as the result, however the program I am trying to run in the /app block is running.

I thought maybe setting the Connection header to Close would solve the problem, but using the code above, which I thought would set the header, still has the Connection header to Keep-Alive

Any help? Thanks!

Vikaton
  • 2,227
  • 3
  • 14
  • 23
  • It seems "done" shoud be placed at the end of the `do ... end` block after all other stuff, so the block should return this value. HTTP header `Connection=close` is far enough from what you need. – andrykonchin Dec 05 '15 at 22:20
  • @andrykonchin I tried that and it doesn't show "done" until after I shut down the server, which shuts down the `./blink` as well, so I still get the long loading loop – Vikaton Dec 05 '15 at 22:27
  • .Are you sure all your shell commands are completed fast and don't delay the response? Can you add some sort of logging to see all lines are executed or some lne are't execited? – andrykonchin Dec 05 '15 at 22:34
  • @andrykonchin Like I said, the `sudo ./blink #{params["func"]}` line is executing a forever running program that does not complete/return – Vikaton Dec 05 '15 at 22:41
  • oh, sure, I got it. Have you tried to detach from the shell process with `&` command like `sudo ./blink #{params["func"]} &`? – andrykonchin Dec 05 '15 at 22:43
  • @andrykonchin Just did, no such luck :( – Vikaton Dec 05 '15 at 22:47
  • Hm, can you check in terminal this command? Your shell comand have to release you terminal at least. Is it true (it releases) the issue is in another place. – andrykonchin Dec 05 '15 at 22:55
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/97093/discussion-between-vikaton-and-andrykonchin). – Vikaton Dec 05 '15 at 23:12

1 Answers1

1

Referencing this SO question Spawn a background process in Ruby and with some help from @andrykonchin, I was able to resolve my issue using this:

pid = fork do
        `sudo ./blink #{params["func"]}`
    end
Process.detach(pid)
Community
  • 1
  • 1
Vikaton
  • 2,227
  • 3
  • 14
  • 23
  • I'd add that unless you want to spawn a new process every time that route is hit, you should consider writing a file (or something) that indicates the process is already running, or allows you to check, and then change the route verb from a GET to a PUT or POST to indicate idempotence. – ian Dec 07 '15 at 13:22