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);
paxdiablo
source share