转载自他人博客
如果多个用户对一个文件进行操作的时候,如何解决,考虑用文件锁的形式和多路复用形式
Linux下多个进程或线程同时对一个文件进行写操作,使用flock(锁定文件或解除锁定),可以解决冲突。
头文件
#include<sys/file.h>
定义函数
int flock(int fd,int operation);
函数说明 flock()会依参数operation所指定的方式对参数fd所指的文件做各种锁定或解除锁定的动作。此函数只能锁定整个文件,无法锁定文件的某一区域。
参数
operation有下列四种情况:
LOCK_SH 建立共享锁定。多个进程可同时对同一个文件作共享锁定。
LOCK_EX 建立互斥锁定。一个文件同时只有一个互斥锁定。
LOCK_UN 解除文件锁定状态。
LOCK_NB无法建立锁定时,此操作可不被阻断,马上返回进程。通常与LOCK_SH或LOCK_EX 做OR(|)组合。 单一文件无法同时建立共享锁定和互斥锁定,而当使用dup()或fork()时文件描述词不会继承此种锁定。
返回值 返回0表示成功,若有错误则返回-1,错误代码存于errno。
程序如下:
#include <sys/file.h> //flock header file
#include <unistd.h> //ftruncate header file
int main(int argc, char *argv[])
{
FILE *fin;
Buf[100] = {“hello world”};
fin = fopen(argv[1], "rt+");
if (!fin)
{
Printf( "Fail to open the file: \n" )l;
return;
}
//建立排他锁,阻塞方式
if ( (flock(fileno(fin), LOCK_EX)) < 0 )
{
Printf("Fail to lock the file: \n");
return;
}
ftruncate(fileno(fin), 0); //清空文件
//写文件
fwrite(buf,sizeof(buf),1,fin);
//解除锁
if ( (flock(fileno(fin), LOCK_UN)) < 0 )
{
printf("Fail to unlock the file: ");
return;
}
fclose(fin);
}