0

Is there any way to check if a file is in use in C/C++? Or do I have to ALWAYS implement a lock/semaphore to prevent simultaneous access of any file by multiple threads/processes?

If we consider Linux, and the following scenario: I want to transfer,in chunks, the contents of a file stored in device A to another device B through RS-232 communication, using a pre-defined communication framework. When the request for this transfer comes, I want to verify the file is NOT being used by any process in device A, before sending a "Ready to Transfer : OK" response, following which I will start reading and transmitting the data in chunks. Is there a way to check file if is already in use without doing fopen/fclose on the said file?

VivereJay
  • 71
  • 8
  • are you asking about how to [check whether a file is used by another application](http://stackoverflow.com/questions/1048592/how-to-check-if-a-file-has-been-opened-by-another-application-in-c)? – Son-Huy Pham Jul 18 '13 at 19:56
  • 6
    It depends on the OS. – Drew McGowen Jul 18 '13 at 19:57
  • Usually any file reader automatically does the lock on the file when you open it. When another file reader tries to open the same file you should get an error, however, this is dependent on the operating system as some will still allow multiple opens. – Lochemage Jul 18 '13 at 19:59
  • 3
    @Lochemage Most modern OSes don't lock files that way. Even on Windows locking is an option which is defaulted to on only for compatibility with ancient versions of DOS. – bames53 Jul 18 '13 at 20:17
  • 2
    "Do or do not; there is no try." The only reliable way to find out if fopen() will work is to do the fopen(). If nothing else, some other process could delete or open the file after your check and before you call fopen(). – Alan Stokes Jul 18 '13 at 21:04

1 Answers1

0

actually

fopen();

is the best way to find this out.

Do fopen() on the receiving end, if it is successful, send the "OK to receive" message.

ctrl-shift-esc
  • 876
  • 1
  • 9
  • 19