用fcntl锁一个文件来保护操作

int testfd; /* fd for test*/

if((testfd = open("/usr/local/pgsql/bin/test_fd",O_RDWR|O_CREAT,0666)<0))
{
perror("open test_fd is error!");
exit(1);
}

/* add fcntl lock function file_lock(int fd,int type) */
void file_lock (int fd,int type)
{
struct flock lock;
lock.l_type = type;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;

while(1)
{
if ((fcntl(fd,F_SETLK,&lock)==0))
{
if (lock.l_type == F_RDLCK)
printf("you got a readlock,the pid = %d",getpid());
if (lock.l_type == F_WRLCK)
printf("you got a writelock,the pid =%d",getpid());
if (lock.l_type == F_UNLCK)
printf("you got a realeselock,the pid = %d",getpid());
return ;/* add lock success and return */
}
/* add lock fail */
fcntl(fd,F_GETLK,&lock); /* get file lock info ,give it to lock */
if (lock.l_type!=F_UNLCK) /* reason of can't add lock */
{
if (lock.l_type == F_RDLCK) /* there is a read lock */
printf("it is already a lock!thd pid =%d ",lock.l_pid);
else if (lock.l_type ==F_WRLCK) /* there is a write lock */
printf("it is already a write lock!the pid =%d ",
lock.l_pid);
//getchar();
}
}
}

file_lock(testfd,F_WRLCK);//加锁

//需要保护的操作

file_lock(testfd,F_UNLCK);//解锁

原文地址:https://www.cnblogs.com/songyuejie/p/3979322.html