[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Sheflug] Running programs on file creation




> A bit of a strange question here, but does anyone know of a way to run a
> program as soon as a file is created in a specific directory?
> 
> Basically I've got a system set up so that every minute the directory
> /var/lock/connect is checked, and if there are any files in there then I get
> connected to the internet, and if there aren't any files in there then I get
> disconnected from the internet. This is done via a crontab entry, and works
> fairly well. The problem is the 1 minute turn-around on
> connection/disconnection attempts. I was just wondering if there's a way of
> doing it automatically on the creation of these files?
> --

Not really (kernel wise). A short shell script could do the job 
though...summat like:

	#!/bin/sh
	while true
	do
		x=`ls /var/lock/connect | wc -l | tr -d ' '`
		if [ $x -ne 0 ]
		then
			echo files exist
		fi
		sleep 1
	done	

Now the line that does the file check is a bit long winded, yes, but I've 
not come across a safe alternative than to just ls and count the number of 
entries in the directory. Doing "[ -f * ]" on ksh works here, but I can't 
gurantee that to be portable between UNIXes...it certainly isn't portable 
between shells.

But save that to a file (say, dirmon), chmod +x it, then at the command 
line "nohup dirmon &" (or "nohup dirmon > dirmon.log 2>&1 &" if you want a 
log file) and it should run. The nohup invocation will ensure that dirmon 
continues running after you log out of your shell.

That will check every 1 second the /var/lock/connect directory. Change the 
'sleep 1' to 'sleep <whatever>' to have it check every <whatever> seconds. 
This must be an integer.

It would also be possible to write something in C that would fstat the 
directory and see if the modification timestamp has changed since the 
program last checked. Again, this would just sleep() or nanosleep() between 
checks.

Chris...

-- 
\ Chris Johnson           \  "If not for me then, do it for yourself. If not
 \ cej [at] nccnet.co.uk        \  for then do it for the world." -- Stevie Nicks
  \ www.nccnet.co.uk/~cej/  ~-----------------------------------------+
   \ Redclaw chat - http://redclaw.org.uk - telnet redclaw.org.uk 2000 \____


___________________________________________________________________

Sheffield Linux User's Group - http://www.sheflug.co.uk . 
To unsubscribe from this list send mail to 
shef-lug-request@list.sheflug.org.uk with the word
"unsubscribe" in the body of the message. 

  GNU the choice of a complete generation.