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:

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 */
       /* perhaps write pid into file */
       /* do access protected by lockfile */

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?

thanks in advance.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.