How determine if a file is opened by another process

Chris Lewis clewis at ferret.ocunix.on.ca
Thu Jan 31 05:26:47 AEST 1991


In article <1991Jan29.204403.6071 at rick.doc.ca> andrew at calvin.doc.ca (Andrew Patrick) writes:
>In article <1488 at nixsin.UUCP> koerber.sin at nixdorf.com writes:

>>I want to find out, whether any process has opened a file, of which I only
>>have the filename (or the inode, and the fs). The process that might have
>>opened it need not be related to mine. I want to find out whether I can
>>delete the file, without creating a still existing, unref'd file, which might
>>grow without me knowing which file it is. I looked through inode.h and ino.h,
>>but found no pointer to this.

>>Could anyone pls give me a hint ?. Maybe it's in a table in the kernel ?

You don't really want to do that.  Though, might be able to do this with
"crash" or "pstat" if your system has either one.  But if the process isn't
related to yours, the O/S probably won't allow you to look at it.  Looking
thru /dev/kmem via the namelist is of course possible, but extremely
O/S specific and has to be done as root.  You would look via the inode
in the inode table and look for the reference count to go to zero (or
the inode disappear from the inode table).  This is a variation of how
fuser might be implemented on a given machine.

>I need to know this too!

>I just got the following question from one of my users:

|    I need to know if there's a standard, *safe* way for a process to
|    find out if some other process (any other process on the machine)
|    has a specific file open at the time of the query.

This is sort of gross, but I would imagine that this would work on
most versions of UNIX.  I'm not sure whether this would work across
a network though.  Do something like:
    
    struct stat stb;
    stat(<filename>, &stb);
    oldmtime = stb.st_mtime;
    while(1) {
	sleep(5);
	stat(<filename>, &stb);
	if (oldmtime == stb.st_mtime)
	    break;
	oldmtime = stb.st_mtime;
    }

This will loop waiting for the file to stop being written to.  You
might have to up the sleep time to something more substantial (on the order
of minutes) to ensure that you don't fall thru simply because the process
got swapped out or stopped printing for a while.  But I think it might
work well enough for your purposes.  This of course won't work for
a file that's open for reading.

As far as worrying about removing the file whilst it's being written to,
I wouldn't worry too much - the file will disappear once the process
closes the file (or dies).  If it doesn't die, you have a different problem.
-- 
Chris Lewis, Phone: (613) 832-0541, Internet: clewis at ferret.ocunix.on.ca
UUCP: uunet!mitel!cunews!latour!ecicrl!clewis
Moderator of the Ferret Mailing List (ferret-request at eci386)
Psroff enquiries: psroff-request at eci386, current patchlevel is *7*.



More information about the Comp.unix.internals mailing list