Forcing code in Ruby on Windows when X button is pressed

When writing a ruby ​​script on Windows (ruby -v outputs ruby ​​1.9.3p545) I ran into an interesting and rather specific problem. I am trying to close an open file if the user exits execution. For example,

begin
f = File.open("monkeys.txt", "w+")
#stuff with the file
rescue Exception => e #I know this is a bad idea
puts e.backtrace
ensure
f.close
end

      

This now works if I terminate the execution with Ctrl + C while doing this in cmd. However, when I press "X" in the cmd prompt window, the code in the provisioning block does not run. I've tried something like ...

at_exit do
f.close if !f.closed?
end

      

... but that still doesn't execute the code I want when the X button is pressed. So what should I do to force the code to "secure" in Ruby if it's closed with that X button?

+3


source to share


1 answer


Well, I don't really program for windows, so I might get lost in the details, but let me try to shed some light on this Linux workaround:

@ppid = Process.ppid
pid = fork do
  loop do
    sleep(1)
    begin
      Process.getsid(@ppid)
    rescue Errno::ESRCH
      File.new("process_down.txt", "a+")
      exit(1)
    end
  end
end

Process.detach(pid)
puts "Process detached"

      



What it means is it creates a forked process, decouples it from the main process and keeps listening when the main process is killed (it will throw Errno :: ESRCH on Process.getsid if @ppid no longer exists), so it will create a .txt file and exit ... I don't know how to handle forking and pids in windows, but this is just to try and show you some possibilities =]

0


source







All Articles