1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include "lockfile.h"
#define LOCKDIR "/var/run"
#define LOCKPREFIX "/zcip."
static void
gen_lockfile_name(char * nbuf, char * device)
{
char * p;
p = strrchr(device, '/');
strcpy(nbuf, LOCKDIR LOCKPREFIX);
if( p ) strcat(nbuf, p+1);
else strcat(nbuf, device);
}
int
lock_check(char * device)
{
FILE * fd;
char nbuf[128];
int i;
gen_lockfile_name(nbuf, device);
fd = fopen(nbuf, "r");
if( fd )
{
fscanf(fd, "%d", &i);
fclose(fd);
if( kill(i, 0) == 0 ) return 0; /* Sorry */
if( errno == EPERM ) return 0;
if( unlink(nbuf) == -1 ) return 0;
}
fd = fopen(nbuf, "w"); /* Got it! */
i = getpid();
fprintf(fd, "%d\n", i);
fclose(fd);
return 1;
}
void
lock_unlock(char * device)
{
FILE * fd;
char nbuf[128];
int i;
gen_lockfile_name(nbuf, device);
fd = fopen(nbuf, "r");
if( fd )
{
fscanf(fd, "%d", &i);
fclose(fd);
if( i == getpid() || kill(i, 0) != 0 )
unlink(nbuf);
}
}
|