Operating System - HP-UX
1834925 Members
2332 Online
110071 Solutions
New Discussion

Re: How to tell IF a file is opened by a process using C code

 
Dan Deck
Advisor

How to tell IF a file is opened by a process using C code

Does anyone know how to do this or have an example in C on how to do this? I want to make sure a file is not opened by a process before I do something with it.
This is on an HPUX 11i OS.
Thanks
5 REPLIES 5
Sundar_7
Honored Contributor

Re: How to tell IF a file is opened by a process using C code

I believe you could use fcntl() call to find out the status of the file.

# man 2 fcntl

# man 5 fnctl
Learn What to do ,How to do and more importantly When to do ?
Dan Deck
Advisor

Re: How to tell IF a file is opened by a process using C code

Do you know of any example code that would demonstrate this?
Ermin Borovac
Honored Contributor

Re: How to tell IF a file is opened by a process using C code

From UNIX programming FAQ at http://www.faqs.org/faqs/unix-faq/programmer/faq/

2.4 How can I find out if someone else has a file open?
=======================================================

This is another candidate for `Frequently Unanswered Questions' because, in
general, your program should never be interested in whether someone else
has the file open. If you need to deal with concurrent access to the file,
then you should be looking at advisory locking.

This is, in general, too hard to do anyway. Tools like `fuser' and `lsof'
that find out about open files do so by grovelling through kernel data
structures in a most unhealthy fashion. You can't usefully invoke them from
a program, either, because by the time you've found out that the file
is/isn't open, the information may already be out of date.
Ermin Borovac
Honored Contributor

Re: How to tell IF a file is opened by a process using C code

fcntl implements advisory locking mechanism that can be used only if all processes accessing a file use this method.
Mike Stroyan
Honored Contributor

Re: How to tell IF a file is opened by a process using C code

Here is a program that will report pids that have particular files open. It uses pstat_getproc and pstat_getfile.