Forcing Code in Ruby on Windows when X button is hit - ruby

While writing a ruby script on Windows (ruby -v outputs ruby 1.9.3p545) I encountered an interesting and rather specific problem. I was attempting to close an opened file if a user terminates 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
Now, this works if I terminate execution via Ctrl+C while running this in cmd. However, when I hit the "X" on the cmd prompt window, the code in the ensure block doesn't run. I tried something like...
at_exit do
f.close if !f.closed?
end
...but that still doesn't execute the code I want it to when the X button is hit.
So, what do I do in order to force "ensure" code in Ruby if it's closed via that X button?

Well, I don't really program for windows, so I might get lost on the details, but let me try to shed some light with this workaround for Linux:
#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 this does is it creates a forked process, detaches it from the main process and keeps listening for when the main process is killed (it'll throw Errno::ESRCH on Process.getsid if the #ppid is no longer there), so it'll create a .txt file and exit. I don't know how to handle forking and pids in windows, but that's just to try and show you some possibilities =]

Related

Track progress of dd command called using open3 in ruby

I am trying to monitor the progress of copying a raspberry-pi OS image to a microSD card. This is similar to Kill a process called using open3 in ruby, except I'm not killing the process, I'm sending it a command for it to issue a progress message.
rpath = device_path.gsub(/disk/, "rdisk")
puts "\n\nCopying image to #{rpath}"
if false
stdout_err, status = Open3.capture2e( "sudo", "dd", "bs=1m", "if=#{source_path}", "of=#{rpath}" )
puts stdout_err
else
cmd = "sudo dd bs=1m if=#{source_path} of=#{rpath}"
Open3.popen2e(cmd) do |stdin, stdout_err, wait_thr|
Thread.new do
stdout_err.each {|l| puts l}
end
Thread.new do
while true
sleep 5
if true
Process.kill("INFO", wait_thr.pid) #Tried INFO, SIGINFO, USR1, SIGUSR1
# all give: `kill': Operation not permitted (Errno::EPERM)
else
stdin.puts 20.chr #Should send ^T -- has no effect, nothing to terminal during flash
end
end
end
wait_thr.value
end
The first section (after 'if false') flashes the image using Open3.capture2e. This works, but of course issues no progress information.
The section after the 'else' flashes the image using Open3.popen2e. It also attempts to display progress by either issuing 'Process.kill("INFO", wait_thr.pid)', or by sending ^T (20.chr) to the stdin stream every 5 seconds.
The Process.kill line generates an "Operation not permitted" error. The stdin.puts line has no effect at all.
One other thing... While the popen2e process is flashing, hitting ctrl-T on the keyboard DOES generate a progress response. I just can't get it to do it programmatically.
Any help is appreciated!
Newer versions of dd have an optional progress bar, as seen here. Even so I think you'll want to rethink how you execute that shell command so that it thinks it's attached to a terminal. Easiest thing to do is fork/exec, like:
cmd = "sudo dd bs=1m if=#{source_path} of=#{rpath} status=progress"
fork do
exec(cmd) # this replaces the forked process with the cmd, giving it direct access to your terminal
end
Process.wait() # waits for the child process to exit
If that's not an option you may want to look into other ways of getting unbuffered output, including just writing a bash script instead of a ruby one.

Ruby exucution stuck at system() line

This is my code snippet
def execution_start
puts "About to start"
system("appium")
puts "Done!!"
end
When executing this I see the output About to start, and appium server is launched. But after that, I do not see anything happening. It's stuck forever. Any idea?
system blocks until the command it runs has completed. To run a command and return immediately, use Process#spawn:
def execution_start
puts "About to start"
pid = Process.spawn("appium")
puts "Done!!"
end
You can then use the returned PID to monitor whether the process has finished executing, and with what exit code, later in your program.
(Note that, per the documentation, you need to Process#wait the PID eventually, or at least register disinterest using Process#detach to prevent the subprocess from becoming a zombie.)

Killing Threads in Ruby Shoes doesn't seem to work?

I try to make this piece of code works in Ruby Shoes, but I can't succeed to kill the thread named "airodump". Each time I click on the "stop scanning" button, it doesn't do anything :s
Thanks
button "scan networks" do
airodump = Thread.new do
`sudo airodump-ng --write tuto wlan0`
end
Thread.new do
button "Stop scanning" do
Thread.kill(airodump)
end
end
end
Thread killing (in any language) is a pretty limited operation. In your case, the thread is stuck in a blocking call - the call to the subshell - and therefore cannot be killed.
What you would need to do is kill the subprocess first. I don't know how to get the PID out of the backtick operator, so you would need to rather use Process.spawn (on ruby 1.9), gey the PID of the subprocess, and call Process.kill
I think the main problem is that you should use class variables so define
#airodump=Thread.new do
...
end
And than kill it by:
Thread.kill(#airodump)

Kill process and sub-processes in Ruby on Windows

Currently I'm doing this in one command prompt
require 'win32/process'
p = Process.spawn("C:/ruby193/bin/bundle exec rails s")
puts p
Process.waitpid(p)
and then in another
require 'win32/process'
Process.kill(1,<p>)
The problem is that the process I spawn (the Rails server in this case) spawns a chain of sub-processes. The kill command doesn't kill them, it just leaves them orphaned with no parent.
Any ideas how can I kill the whole spawned process and all its children?
I eventually solved this in the following manner
First I installed the sys-proctable gem
gem install 'sys-proctable'
then used the originally posted code to spawn the process, and the following to kill it (error handling omitted for brevity)
require 'win32/process'
require 'sys/proctable'
include Win32
include Sys
to_kill = .. // PID of spawned process
ProcTable.ps do |proc|
to_kill << proc.pid if to_kill.include?(proc.ppid)
end
Process.kill(9, *to_kill)
to_kill.each do |pid|
Process.waitpid(pid) rescue nil
end
You could change the kill 9 to something a little less offensive of course, but this is the gist of the solution.
One-script solution without any gems. Run the script, CTRL-C to stop everything:
processes = []
processes << Process.spawn("<your process>")
loop do
trap("INT") do
processes.each do |p|
Process.kill("KILL", p) rescue nil
Process.wait(p) rescue nil
end
exit 0
end
sleep(1)
end

Troubles with parallel processes in IRB on Mac

I am working with a database via IRB, and I would like to make periodic changes in the database (e.g., every 10 sec) showing the log in STDOUT.
Also, I would like to have manual control being able to change the database and to stop the first process.
So far I came up to the following
def start
stop
#running = Thread.new do
loop do
fork do
puts 'change the database'
end
sleep 10
end
end
nil
end
def stop
#running.kill if #running
end
However, this is not running every 10 sec unless I enter something in the main IRB thread.
How to make it working?
Some versions of readline on OSX are blocking. If one experiences the behavior you described, they can disable readline by putting
IRB.conf[:USE_READLINE] = false
in .irbrc
Works fine for me (tested in irb with ruby 1.9.2-p180 and 1.8.7-p334).

Resources