1

I'm working on a piece of code which monitors a directory and performs certain tasks when a new file is created in that directory. I'm using FSSM and my (simplified) code looks like this:

require 'fssm'

class FileWatcher

def initialize

    FSSM.monitor('./temp/', '**/*', :directories => true) do
        create do |base, relative|
            puts "Create called with #{relative}"
        end
    end
end
end

FileWatcher.new

The file monitoring aspect works well, but my problem is when I halt this script. What happens is the "file_monitor" process remains running. E.g. this is after running and halting the script 3 times:

$ ps aux | grep file_watcher
root      3272  1.0  5.3   9760  6596 pts/0    Tl   00:11   0:02 ruby file_watcher.rb
root      3302  1.5  5.2   9760  6564 pts/0    Tl   00:14   0:02 ruby file_watcher.rb
root      3314  2.2  5.2   9764  6564 pts/0    Sl+  00:14   0:02 ruby file_watcher.rb

I.e. there are 3 processes still running. So, how to clean up upon exit of the script?

barry
  • 4,037
  • 6
  • 41
  • 68

1 Answers1

1

Install a signal handler in the father process which triggers when it is about to get killed by a signal (SIGINT, SIGTERM, SIGQUIT, SIGHUP) and which then in turn sends an appropriate signal to the child process (FSSM monitor).

Alfe
  • 56,346
  • 20
  • 107
  • 159
  • Sounds promising. Any chance of some code samples? I.e. How do I listen for a kill signal then how do I kill the child process? – barry Jan 29 '14 at 00:48
  • See [here](http://www.ruby-doc.org/core-2.1.0/Signal.html) for signal handling. Sending a process a signal is done via `Process.kill`. – Alfe Jan 29 '14 at 01:05
  • Thanks for this. I didn't manage to get this working but found an easier route for my needs - as my script will run the whole time the machine is running I'll just launch it at reboot and it'll be killed at power down. I'll mark this as accepted. – barry Jan 30 '14 at 10:51