Sorted this out once I understood exec better:

   pid = fork
   if (pid == nil)
     # child
     exec(cmd)
   else
     # parent
     Signal.trap("SIGINT") do
       Process.kill(9,pid) # kill child
       puts "Removing #{outfile}..."
       FileUtils.rm(outfile)
       Process.kill(9,0)   # kill self
     end
     begin
       Process.waitpid(pid)
     rescue
       puts "Whateeever..."
     end
   end

Any comments on this? The right way to do things?

Sonia Hamilton wrote:
(Ruby 1.9)

In a script, I would like to repeatedly start up a long running subprocess, but only have one subprocess running at a time. If I send my script an interrupt (ctrl-c), I'd like to kill the subprocess, clean up some files, and exit my script. I've been playing with fork, wait, exec, spawn, threads and trap - not getting very far...

I guess my real source of confusion is when I send through the ctrl-c, is it first caught by my script or the subprocess?

How do I do this? Anyone have some sample code?

This is how I thought I'd do it, but when I ctrl-c the output just flashes and the script keeps running :-(

   pid = spawn(cmd)
   Signal.trap(2) do     # SIGINT, ctrl-c
     puts "Removing #{outfile}..."
     FileUtils.rm(outfile)
     Process.kill(9,pid) # kill subprocess
     Process.kill(9,0)   # kill self
   end
   waitpid(pid, Process::WNOHANG) # only have one subprocess at a time

The commands (cmd) look like this (high cpu video processing, so I only want 1 running at once):

handbrake -i foo/VIDEO_TS --preset='Normal' --longest --chapters 7 --output mp4/foo.7.mp4


--
You received this message because you are subscribed to the Google Groups "Ruby or 
Rails Oceania" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rails-oceania?hl=en.

Reply via email to