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 */
               sleep(1);
       }
       /* perhaps write pid into file */
       close(fd);
       /* do access protected by lockfile */
       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.

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.

This article has been dead for over six months. Start a new discussion instead.