- 论坛徽章:
- 0
|
兄弟,加上写锁就好了。
给你一个代码。
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc,char* argv[])
{
int fd;
struct flock lock;
int count = 0;
if(argc != 2)
{
printf("Usage: %s filename.\n",argv[1]);
return 1;
}
fd = open(argv[1],O_RDWR);
if(fd<0)
{
printf("Open file failed.\n" ;
return 1;
}
lock.l_type = F_WRLCK;
lock.l_whence = 0;
lock.l_start = 0;
lock.l_len = 0;
while(fcntl(fd,F_SETLK,&lock)<0)
{
if(errno == EAGAIN||errno == EACCES) //被其他进程加锁了
{
if(++count<5)
sleep(1); //加锁申请最多持续5s
else
{
fcntl(fd,F_GETLK,&lock);
printf(" id: %ld process find pid %ld process lock the file %s.\n",
(long)getpid(),(long)lock.l_pid,argv[0]);
return 1;
}
}
else
{
printf("Error: exec function fcntl failed.\n" ;
return 1;
}
}
printf(" id: %ld process locked the file.\n",(long)getpid());
sleep( ; //占用文件的时间,这里可以是对文件的一些操作
printf(" id: %ld process release the file.\n",(long)getpid());
return 0;
}
[ 本帖最后由 kwaz 于 2009-9-16 21:28 编辑 ] |
|