Search code examples
rubyunixlsof

How to know if an image file is open


Hello i would like to make a small ruby script to alert me when my image is open.

i try with :

filename = "photo.jpg"

loop do
    sleep(1)
    if system %Q[lsof #{filename}]
        puts "File open"
    end
end

But it's not working.. any idea ?


Solution

  • Try this example:

    1. Create a file touch hello_world.log
    2. Tail the file with -f (allows you to follow the file in real time as it grows) tail -f hello_world.log
    3. Open a separate terminal and open up irb

    Enter the following code:

    filename = "hello_world.log"
    
    loop do
        sleep(1)
        if system %Q[lsof #{filename}]
            puts "File open"
        end
    end
    

    You may wish to have a look at inotify (Ruby gem rb-inotify) as this might be what you want instead. Assume a scenario whereby someone opens a file with a text editor and then saves it, the save event might not show up under lsof as it's polling every second (and will subsequently only show information that was present at that very point, so you may never catch it).