joele24
asked on
Single Program Instance
How can I make some sort of lock to ensure that only one instance of a program is running at a time?
ASKER
I have the 2nd way you described but the problem is I appear to be hitting a race condition where 2 will start up and one both will read and write to the file in such a way as to miss that another process is running
if you running on windows you can use named mutex object
On linux you don't need to write to the file. Simply open it for exclusive write. The second program will be unable to open the file because it's "locked" and know that another instance is running.
When the program terminates the lock file will automatically be closed so there's no chance of a deadlock or improper status in the file.
Kent
plz have a look at the following links
http://www.codeproject.com/cpp/avoidmultinstance.asp
http://www.deinmeister.de/wasmfaq_e.htm
i hope they may be of any help
BOl
http://www.codeproject.com/cpp/avoidmultinstance.asp
http://www.deinmeister.de/wasmfaq_e.htm
i hope they may be of any help
BOl
ASKER
This is for the linux platform, but thx for all the additonal info.
Kdo,
so what is wrong with this?
mutex= open("/path/to/file",O_RDW R|O_EXCL);
basically as I run multiple instances of the program they all are able to get this file descriptor and do not return -1
Kdo,
so what is wrong with this?
mutex= open("/path/to/file",O_RDW
basically as I run multiple instances of the program they all are able to get this file descriptor and do not return -1
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
ah one quick question do you know if i can call a system("touch path_to_file") or will the lock prevent this
You should be able to do that. If the touch(1) fails (which it shouldn't) the worst that will happen is that system() will return a non-zero value.
The other way can be writing some information (e.g. process ID) into some file and everytime before starting just check whether that file exists. Similarly you need to remove that file just before the program is exiting.