Saturday, July 25, 2009

File Access Times as Debugging Tools

"Is that configuration file actually being read? I'm sure I changed it. Maybe I'm just not reading the data file I think I am."

"Is my command actually being executed? Is my initialization script getting executed first?"

I use the Linux "file access time" as a debugging tool.

If you want to know the last time a file was written, ls -l tells you the time. You knew that.

If you want to know the last time a file was read (or was run, if it's an executable), ls -ul tells you the time. Maybe you didn't know that.

Or the last time a particular app is getting invoked. The access time tells you when an executable was run because Linux has to read it to execute it.

Or, at least, it used to work this way. Newer Linux systems no longer do, but you can still get the information you need. I'll show you how.

On newer systems, the access time (the time ls -ul reports) is the last time a file was read after the last time it changed. You can get the same information, it just takes a little more setup work. Here's a script that shows how:

#!/bin/bash -x

PS4='$(date +%H:%M) $ '
: == Create a file at a well-defined time.
rm -f /tmp/foo
touch /tmp/foo
: == File write and access times are the same.
ls -l /tmp/foo; ls -ul /tmp/foo
: == Sleep, so the time changes, and read the file
sleep 60; cat /tmp/foo
: == The access time is now later than the write time.
ls -l /tmp/foo; ls -ul /tmp/foo
: == Do it again.
sleep 60; cat /tmp/foo
: == The access time DOES NOT change, because There was no intervening write.
ls -l /tmp/foo; ls -ul /tmp/foo
: == Now "write" the file.
touch /tmp/foo
: == Sleep so the time changes, and read it.
sleep 60; cat /tmp/foo
: == This time, the time does change.
ls -l /tmp/foo; ls -ul /tmp/foo
The meaning of access time was changed as an efficiency hack, so that inodes aren't re-written as often.

In the script, I'm using ':' as a comment character. I should explain why, but I'll leave that as a separate post. Or, you could run the script to see. :-)

No comments: