Linux file locks

I tried using temporary files:

char *temp = tempnam(NULL, "myapp_"); printf("Tempname: %s", temp) // Prints /tmp/myapp_random while (1) { } 

But when I check /tmp (while the application is still running), myapp_random does not exist!

As with file locks, I can't figure it out, I tried looking at <fcntl.h> , but it seems to focus on locks in certain parts of the file. I just want to use the entire file as a lock (which is why I prefer to use a temporary file).

Any ideas?

+7
source share
1 answer

tempnam does not create a file, it just gives you the name of a file that you didnโ€™t have at the time you named it.

You still need to create the file yourself and, therefore, still have a race condition that another process can penetrate and create it in front of you.

In fact, you do not want to use tempnam , as this will give each process its own file name, and they will work simultaneously. You need a fixed file name (e.g. /tmp/myapp.lck ) that is opened by each process and then flock tries.

Better with flock for the lock file, fcntl will give you a finer grain of lock (parts of the files), but this is not quite a requirement here.

The code will work something like this:

 if ((mylockfd = open ("/tmp/myapp.lck", O_CREAT | O_RDWR, 0666)) < 0) { // error, couldn't open it. return; } if (flock (mylockfd, LOCK_EX | LOCK_NB) < 0) { // error, couldn't exclusive-lock it. return; } : // Weave your magic here. : flock (mylockfd, LOCK_UN); 

This probably needs some work, but should be a good start. A more generalized solution would look something like this:

 int acquireLock (char *fileSpec) { int lockFd; if ((lockFd = open (fileSpec, O_CREAT | O_RDWR, 0666)) < 0) return -1; if (flock (mylockfd, LOCK_EX | LOCK_NB) < 0) { close (lockFd); return -1; } return lockFd; } void releaseLock (int lockFd) { flock (lockFd, LOCK_UN); close (lockFd); } // Calling code here. int fd; if ((fd = acquireLock ("/tmp/myapp.lck")) < 0) { fprintf (stderr, "Cannot get lock file.\n"); return 1; } // Weave your magic here. releaseLock (fd); 
+9
source

All Articles