[LCP]How to tell if a file is open?

David Spencer David.W.Spencer at oracle.com
Fri Sep 21 20:03:50 UTC 2001


Open the file for exclusive write.  If the file is open (other than for
read access) this will fail; otherwise you then have an exclusive lock
on the file, which is presumably what you want to do next, not to
mention the obvious flaw in the following logic:

see if the file is open some other way
acquire exclusive lock for writing.


If these two steps are interrupted then some other program may just
acquire an exclusive lock just as you've determined it is safe to do
exactly that, then this logic will fail and it won't be immediately
obvious why.

Of course this isn't a problem on a single user system (but then the
original question is also irrelevant on a single user system.)

Dave.



David Filion wrote:
> 
> I'm writing a routine that need to check if the stream it is writing to is open
> before it writes to it.  for example,
> before I try to write and error messge to stdout, I want to make sure it is
> still open.  How can I do this?  All the
> file status functions I've come across require an open file.
> (I remember reading how to somewhere but I can't remember where.)
> 
> Thanx.
> 
> ps. Sorry if your getting this twice.  My first post did not seem to get
> processed.
> 
> _______________________________________________
> This is the Linux C Programming List
> :  http://lists.linux.org.au/listinfo/linuxcprogramming List



More information about the linuxCprogramming mailing list