/*************************************************************
FileName : LockFile.c
FileFunc : 实现文件的记录锁,对文件中的值进行加1
Version : V0.1
Author : Study
Date : 2012-05-11
Descp : Linux下对文件的某一记录进行上锁
*************************************************************/
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
int LockInit(char *pathname);
int LockWait();
int LockRelease();
long GetLocalSerial(char* ptrLocalSerial);
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
static struct flock lock_it, unlock_it;
static int lock_fd = -1;
int LockInit(char *pathname)
{
char lock_file[150];
memset(lock_file,0,sizeof(lock_file));
strncpy(lock_file,pathname,sizeof(lock_file));
mkstemp(lock_file);
if((lock_fd=open(lock_file,O_CREAT|O_WRONLY,FILE_MODE))<0)
{
perror("open");
return -1;
}
printf("LockInit:lock_fd = %d \n",lock_fd);
unlink(lock_file);
lock_it.l_type=F_WRLCK;
lock_it.l_whence=SEEK_SET;
lock_it.l_start=0;
lock_it.l_len=0;
unlock_it.l_type=F_UNLCK;
unlock_it.l_whence=SEEK_SET;
unlock_it.l_start=0;
unlock_it.l_len=0;
return 0;
}
int LockWait()
{
int rc;
while((rc=fcntl(lock_fd,F_SETLKW,&lock_it))<0)
{
printf("LockWait:rc = %d \n",rc);
if(errno==EINTR)
continue;
else
return -1;
}
return 0;
}
int LockRelease()
{
if(fcntl(lock_fd, F_SETLKW, &unlock_it)<0)
return -1;
return 0;
}
long GetLocalSerial(char* ptrLocalSerial)
{
char tmp1[100];
char buf[100];
int fd,iRetCode;
long iMaxSerial;
memset(tmp1,0,sizeof(tmp1));
//sprintf(tmp1,"%s/etc/serialfile",getenv("HOME"));
sprintf(tmp1,"%s/serialfile",getenv("PWD"));
printf("tmp1 = %s \n",tmp1);
LockInit("./tmp");
fd=open(tmp1,O_RDWR);
printf("GetLocalSerial:fd = %d \n",fd);
memset(buf,0,sizeof(buf));
iRetCode=LockWait();
printf("GetLocalSerial:iRetCode = %d \n",iRetCode);
read(fd,buf,6);
iMaxSerial=strtol(buf,0,10)+1;
if(iMaxSerial==999999)
iMaxSerial=0;
sprintf(ptrLocalSerial,"%06ld",iMaxSerial);
lseek(fd,0,0);
write(fd,ptrLocalSerial,6);
close(fd);
iRetCode=LockRelease();
return iMaxSerial;
}
int main(int argc,char *argv[])
{
long lSerialNumber;
char szSerialNumber[30];
memset(szSerialNumber,0,sizeof(szSerialNumber));
lSerialNumber = GetLocalSerial(szSerialNumber);
printf("lSerialNumber = %d \n",lSerialNumber);
return 0;
}