| | |
newbie: lock file so only one instance of program runs
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Jan 2007
Posts: 58
Reputation:
Solved Threads: 0
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:
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.
I came across this code:
c Syntax (Toggle Plain Text)
for (tries = 0; tries != maxtries; ++tries) { fd = open("/tmp/some.lock.file", O_WRONLY|O_CREAT|O_EXCL, 0644); if (fd != -1) break; if (errno != EEXIST) { /* do some sort of error handling here... */ } /* perhaps open file for read w/o E_EXCL and read pid */ /* and kill(pid, 0) to check if process died with lock */ sleep(1); } /* perhaps write pid into file */ close(fd); /* do access protected by lockfile */ unlink("/tmp/some.lock.file");
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.
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.
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.
![]() |
Other Threads in the C++ Forum
- Previous Thread: Templates -- Need major help please!!
- Next Thread: lists vs. arrays?
| Thread Tools | Search this Thread |
Tag cloud for C++
api application array arrays based beginner binary bmp c++ c/c++ calculator char char* class classes code compile compiler console conversion convert count data delete deploy dll download dynamiccharacterarray email encryption error file format forms fstream function functions game givemetehcodez graph homeworkhelp iamthwee ifstream input int java lib library lines list loop looping loops map math matrix memory newbie news number numbertoword output pointer problem program programming project python random read recursion recursive reference return rpg search simple sorting spoonfeeding string strings struct temperature template templates text text-file tree url variable vector video visual visualstudio void win32 windows winsock wordfrequency wxwidgets






