#include #include #include #include #include #include #include #include #include "gnumeric.h" gboolean acquire_lock(const char* filename) { char *lockfile; gboolean retval = FALSE; int fd; g_return_val_if_fail(filename != NULL, FALSE); g_return_val_if_fail(strlen(filename) != 0, FALSE); if( is_locked(filename) == TRUE ) { return FALSE; } lockfile = g_malloc(strlen(filename) + 5); strcpy(lockfile, filename); strcat(lockfile, ".lck"); if ((fd = open(lockfile, O_WRONLY|O_CREAT|O_EXCL, S_IREAD|S_IWRITE)) >= 0) { /* Lock succeeded */ char *lockstr; char hostname[256]; int stringsize; // size of locking string long pid; /* Create the locking string, format is * hostname:pid * FBK 15-9-2002: cleanup memory allocation and pid use */ gethostname(hostname, 255); pid = (long) getpid(); stringsize = strlen(hostname) + ( 4 * sizeof (long) ) +1; lockstr = g_malloc(stringsize); snprintf(lockstr, stringsize, "%s:%ld", hostname, pid); printf("DEBUG: Locking %s with %s\n", lockfile, lockstr); write(fd, lockstr, strlen(lockstr)); close(fd); g_free(lockstr); retval = TRUE; } g_free(lockfile); return retval; } gboolean relinquish_lock(const char* filename) { char *lockfile; gboolean retval = FALSE; int fd; g_return_val_if_fail(filename != NULL, FALSE); g_return_val_if_fail(strlen(filename) != 0, FALSE); lockfile = g_malloc(strlen(filename) + 5); strcpy(lockfile, filename); strcat(lockfile, ".lck"); if ((fd = open(lockfile, O_RDONLY)) >= 0) { char lockstr[300] = "\0"; int pid = 0; if (read(fd, lockstr, 300) >= 0) { char *hostname1; char *pidstr; int index; char hostname2[256] = "\0"; gethostname(hostname2, 255); index = strchr(lockstr, ':') - lockstr; if (index > 0) { lockstr[index] = '\0'; hostname1 = lockstr; pidstr = lockstr + index + 1; pid = atoi(pidstr); } printf("hostname = %s, pid = %d\n", hostname1, pid); if ((getpid() == pid) && (strcmp(hostname2, hostname1) == 0)) { printf("DEBUG: Relinquishing lock to %s!\n", filename); close(fd); /* Unlink the lockfile */ unlink(lockfile); retval = TRUE; } else { /* Not ours to relinquish */ printf("DEBUG: Lock file %s is not ours!\n", lockfile); close(fd); } } else { printf("DEBUG: error during read (%d)\n", errno); close(fd); } } else { printf("DEBUG: Lock file %s doesn't exist!\n", lockfile); } g_free(lockfile); return retval; } gboolean is_locked(const char* filename) { char *lockfile; gboolean retval = FALSE; int ret; struct stat st; g_return_val_if_fail(filename != NULL, FALSE); g_return_val_if_fail(strlen(filename) != 0, FALSE); lockfile = g_malloc(strlen(filename) + 5); strcpy(lockfile, filename); strcat(lockfile, ".lck"); if ((ret = stat(lockfile, &st)) >= 0) { retval = TRUE; } return retval; }