newbie: lock file so only one instance of program runs

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Jan 2007
Posts: 58
Reputation: jobs is an unknown quantity at this point 
Solved Threads: 0
jobs jobs is offline Offline
Junior Poster in Training

newbie: lock file so only one instance of program runs

 
0
  #1
Dec 15th, 2007
I need to create a program and have it create a lock file so that only one instance of the program can be run at any one time.

I came across this code:
  1. for (tries = 0; tries != maxtries; ++tries) {
  2. fd = open("/tmp/some.lock.file", O_WRONLY|O_CREAT|O_EXCL, 0644);
  3. if (fd != -1) break;
  4. if (errno != EEXIST) {
  5. /* do some sort of error handling here... */
  6. }
  7. /* perhaps open file for read w/o E_EXCL and read pid */
  8. /* and kill(pid, 0) to check if process died with lock */
  9. sleep(1);
  10. }
  11. /* perhaps write pid into file */
  12. close(fd);
  13. /* do access protected by lockfile */
  14. unlink("/tmp/some.lock.file");
I am not familiar with linux gnu c.

Can someone explains to me what is happening inside the for loop?
What value do I define maxtries equal to?
What is EEXIST?
What is O_WRONLY|O_CREAT|O_EXCL mean?

thanks in advance.
Last edited by jobs; Dec 15th, 2007 at 11:13 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2007
Posts: 1,953
Reputation: Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of 
Solved Threads: 214
Featured Poster
Duoas's Avatar
Duoas Duoas is offline Offline
Posting Virtuoso

Re: newbie: lock file so only one instance of program runs

 
0
  #2
Dec 16th, 2007
You are looking at a not-so-great attempt at creating an application mutex. There is no OS support for such a thing in *nix, so the traditional way to do it is to create a "lock file", hence the flags (particlularly O_EXCL, or 'exclusive access').

A better algorithm is here, as it can withstand program crashes --it doesn't need to clean up after itself.

There is also "gtkunique" (google it), a small library that does nice stuff for you.

Hope this helps.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the C++ Forum
Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC