0

Is there a 'reference count' on a file that maintains how many processes are opening a file in C/C++? Or is there any alternative approach to do so? I've looked at fstat but it seems that it doesn't provide such information.

Ziqi Liu
  • 2,931
  • 5
  • 31
  • 64
  • I'd be interested to hear how it is possible to open a file by more than one handle / process? – nada Jul 24 '19 at 19:33
  • @nada You just call `open` on it. – melpomene Jul 24 '19 at 19:34
  • Didn't know this was possible :O – nada Jul 24 '19 at 19:35
  • 4
    A single process can open the same file multiple times; multiple processes can open the same file too. A process can duplicate a file descriptor easily. Processes fork, which duplicates the file descriptors, and may or may not close the file after forking. There isn't an easy way to get the number you're looking for. It isn't even particularly clear what number you _are_ looking for. It might be the number of open file descriptors, or the number of open file descriptions (that's different) or the number of processes with at least one open file descriptor, or description, or … – Jonathan Leffler Jul 24 '19 at 19:36
  • 6
    If you don't need it programmatically just use `lsof`. – tadman Jul 24 '19 at 19:37
  • 1
    Or `fuser` if `lsof` seems like overkill ... – tink Jul 24 '19 at 19:58
  • @JonathanLeffler We can assume no `fork` and one process will open only one time. Actually I just want to use a file to keep track of a group of processes who is still alive, so every process will open that file when it start. – Ziqi Liu Jul 24 '19 at 20:01
  • 1
    Candidate originals [here](https://stackoverflow.com/questions/22803498/how-can-i-see-how-many-times-i-have-used-fopen-on-a-file) and [here](https://stackoverflow.com/questions/24546155/determine-how-many-times-file-is-mapped-into-memory). Of course, the information is stale immediately upon acquisition, as other processes can open or close a file at any moment. – Eric Postpischil Jul 24 '19 at 20:04
  • You are going to need to use some Linux API (if one exists). Both the C and C++ (separate languages), don't have standard functionality to query file attributes. – Thomas Matthews Jul 24 '19 at 21:10
  • 1
    File status is not intended for IPC (Inter-Process Communication). And IPC is what you need. See https://stackoverflow.com/a/404622/8074683. – Fusho Jul 25 '19 at 10:24
  • May I ask what is your purpose for accessing it? – Alex Wang Aug 19 '19 at 12:10

0 Answers0