LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Locking and unlocking a file (https://www.linuxquestions.org/questions/programming-9/locking-and-unlocking-a-file-554800/)

Jacko123 05-17-2007 10:36 PM

Locking and unlocking a file
 
Hi all,

How can I restrict a user to open the same file on multiple instances of the same application???? If you have word installed, then open multiple instances of it and try opening the same file on all the application...The user is restricted. How can I achieve this???

NOTE: I'm not looking how microsoft have implemented that but looking for a portable solution which can work both on windows and linux.

After search on google I came to know that I need to lock the file( exclusive lock) and then unlock again. I came across this link
http://msdn2.microsoft.com/en-us/lib...4f(VS.80).aspx

That link uses
Quote:

void _lock_file(FILE* file);
. In my application I use ifstream to read a file. I dont have any FIlE*.
So can anyone there tell me how can I lock a file using ifstream or some solution where I can restrict the user to open the same file on different instances of same application.

Thanks

sibtay 05-17-2007 10:55 PM

Quote:

Originally Posted by Jacko123
How can I restrict a user to open the same file on multiple instances of the same application????

If the locking is to be restricted for the same application you dont need anything complex. You can achieve this simply by associating an integer variable for each opened file, or just one array(or other appropiate data structure) for all opened files.

However If you want to restrict other programs to open the file which have been opened by your application take a look at the man pages of fcntl and flock.

sibtay 05-17-2007 10:58 PM

Forgot to add, you can use semaphore sets to provide locking for multiple instances (processes if I understand you correctly) of the same application.

Jacko123 05-17-2007 11:14 PM

Quote:

Originally Posted by sibtay
Forgot to add, you can use semaphore sets to provide locking for multiple instances (processes if I understand you correctly) of the same application.

I didnt get you. Can you be more clear about that...if possible with some examples

Thanks

sibtay 05-18-2007 08:41 AM

Semaphores (or semaphore sets) are the conventional IPC locking mechanism. If you are looking to provide locking for multiple instances of your application you should use semaphore sets.

I dont have the time to write code examples for you, most of the help you'll find here is just guidance. You have to do your work by yourself.

Read about semaphores and IPC. Following are the first two links revealed from a google search on semaphores:

http://www.cs.cf.ac.uk/Dave/C/node26.html
http://www.ecst.csuchico.edu/~beej/g...emaphores.html


All times are GMT -5. The time now is 07:38 PM.