Running code when a file is read?

3 respostas [Última entrada]
Soon.to.be.Free
Desconectado
Joined: 07/03/2016

Hi!

Is there any relatively straightforward way of creating a file that, whenever it's read, runs a (BASH) script and returns STDOUT as the contents? By 'read', I mean simply opened by standard GNU libraries, which kind of complicates the process (e.g. the standard 'chmod +x' and '#!/bin/bash' isn't sufficient).

So far I've found two ways, neither of which ideal:
*Write a custom file driver: Compiling a C program and adding it to the kernel would seem rather excessive for this purpose, even if it weren't high above my current level of knowledge.

*Set up a monitor script on startup, using a named pipe: It's more achievable, but seems needlessly platform-dependent. Furthermore, relying on a script sitting in the background seems wasteful.

Thanks in advance!

Magic Banana

I am a member!

I am a translator!

Desconectado
Joined: 07/24/2010

It is not that wasteful if you add a 'sleep' in your polling loop. Something like:

#!/bin/sh
while true
do
old=$(stat -c %X file)
while [ $(stat -c %X file) = $old ]
do
sleep 2.5
done
# Your code
done

Here, the code will be executed at most 2.5s after the access. Or do you really need the code to be executed immediately?

Soon.to.be.Free
Desconectado
Joined: 07/03/2016

No, 2.5s isn't going to be a problem. Thank you for that!

Magic Banana

I am a member!

I am a translator!

Desconectado
Joined: 07/24/2010

Well, 2.5 is only an example. To waste as little CPU resources as possible, you should set the amount of time to the highest acceptable delay between the access to the file and the execution of the code.