Linux下对文件的某一记录进行上锁

48 篇文章 0 订阅

 

 

/*************************************************************    
    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;
}


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值