This is lock_file.c in view mode; [Download] [Up]
/*
* lock_file - functions for file locking
*
* You may freely copy, distribute and reuse the code in this example.
* This code is provided AS IS without warranty of any kind, expressed
* or implied, as to its fitness for any particular use.
*
* Copyright 1995 Ralph Zazula (rzazula@next.com). All Rights Reserved.
*
*/
#include "lock_file.h"
#include <libc.h>
#include <stdio.h>
#include <errno.h>
int lock_file(char *filename)
/*
* Drops a lock file "filename.lock" for "filename". Returns:
* LOCK_SUCCESS (0) success
* LOCK_EXIST (-1) lock file already exists
* LOCK_NOCREATE (-2) couldn't create lock file
*/
{
int fd;
char lockfile[MAXPATHLEN+1];
sprintf(lockfile, "%s.lock", filename);
fd = open(lockfile, O_RDWR | O_CREAT | O_EXCL, 0660);
if(fd < 0) {
if(errno == EEXIST) {
/* check age of lock file */
struct stat st;
if(!stat(lockfile, &st)) {
if((time(NULL) - st.st_mtime) >= 3600) {
#ifdef DEBUG
fprintf(stderr, "removing stale lock file for %s\n",filename);
#endif
unlink(lockfile);
fd = open(lockfile, O_RDWR | O_CREAT | O_EXCL, 0660);
if(fd < 0) {
if(errno == EEXIST) {
#ifdef DEBUG
fprintf(stderr, "couldn't remove lock file for %s\n",filename);
#endif
} else {
#ifdef DEBUG
fprintf(stderr, "couldn't create lock file for %s\n",filename);
#endif
}
return LOCK_NOCREATE;
} else {
close(fd);
return LOCK_SUCCESS;
}
} else {
return LOCK_EXIST;
}
} else {
#ifdef DEBUG
fprintf(stderr, "couldn't stat %s\n",lockfile);
#endif
return LOCK_EXIST;
}
} else {
#ifdef DEBUG
fprintf(stderr, "cannot create lock file %s\n", lockfile);
#endif
return LOCK_NOCREATE;
}
} else {
close(fd);
}
return LOCK_SUCCESS;
}
int unlock_file(char *filename)
/*
* removes the lock file "filename.lock" for "filename".
* Returns LOCK_SUCCESS on success and a negative error code on failure.
* The error code is that which resulted from the attempted unlink().
*/
{
char lockfile[MAXPATHLEN+1];
sprintf(lockfile, "%s.lock", filename);
if(!unlink(lockfile)) {
return LOCK_SUCCESS;
}
return errno;
}
These are the contents of the former NiCE NeXT User Group NeXTSTEP/OpenStep software archive, currently hosted by Netfuture.ch.