Andres
Andres

Reputation: 11747

Run a process each time a new file is created in a directory in linux

I'm developing an app. The operating system I'm using is linux. I need to run if possible a ruby script on the file created in the directory. I need to keep this script always running. The first thing I thought about is inotify:

The inotify API provides a mechanism for monitoring file system events. Inotify can be used to monitor individual files, or to monitor directories.

It's exactly what I need, then I found "rb-inotify", a wrapper fir inotify.

Do you think there is a better way of doing what I need than using inotify? Also, I really don't understand the way that I have to use rb-inotify.

I just create, for example, a rb file with:

notifier = INotify::Notifier.new
notifier.watch("directory/to/check",:create) do |event|
    #do task with event.name file
end

notifier.run

Then I just ruby myRBNotifier.rb, and it will stay looping for ever. How do I stop it? Any idea? Is this a good approach?

Upvotes: 0

Views: 1578

Answers (3)

Alfie Hanssen
Alfie Hanssen

Reputation: 17094

If you're running on a mac/unix machine, look at the launchctl man page. You can set up a process to run and execute a ruby script whenever a file changes. It's highly configurable.

Upvotes: 0

the Tin Man
the Tin Man

Reputation: 160551

I'd recommend looking at god. It's designed for this sort of task, and makes it pretty easy to build a monitoring system for background and daemon apps.

As for the main code itself, inotify isn't cross-platform, so if you have a possibility you'll need to run on Windows or Mac OS then you'll need a different solution. It's not too hard to write a little piece of code that checks your target directory periodically for a change. If you need to know what changed, read and cache the directory entries then compare them the next time your code runs. Use sleep between runs to wait some period of time before looping.

The old-school method of doing similar things is to use cron to fire off a job at regular intervals. That job can be your script that checks whether the file list changed by comparing it to the cached version, then acting as needed if something is different.

Upvotes: 2

jboursiquot
jboursiquot

Reputation: 1271

Just run your script in the background with

ruby myRBNotifier.rb &

When you need to stop it, find the process id and use kill on it:

ps ux
kill [whatever pid your process gets from the OS]

Does that answer your question?

Upvotes: 0

Related Questions