linux 下多线程给文件加排他锁
利用flock 函数,具体用户请自己查。
执行流程
1,创建 /dev/shm/test文件,并打开文件。
2,fork 一个子进程
在子进程中再次打开文件,目的是不和父进程使用不一样的文件描述符。
3,父子进程各自给文件加排他锁并sleep10秒,
然后向文件中写入数据。
代码如下
/* slock.c */
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
int main()
{
int fd = open( "/dev/shm/test",O_CREAT|O_RDWR,S_IRWXU|S_IRGRP|S_IWGRP|S_IRWXO );
if ( fd < 0 )
{
puts( "open error" );
return -1;
}
if (fork () == 0) {
int fd1 = open( "/dev/shm/test",O_RDWR);
if(flock(fd1,LOCK_EX)==0){
printf("pid(%d) %s",getpid(), "the file was locked by child .\n");
puts( "child sleep now ..." );
sleep( 10 );
write(fd, "child\n",strlen("child\n"));
if(flock(fd1,LOCK_UN)==0){
puts("child the file was unlocked .\n");
}
}
close( fd1);
puts( "child exit..." );
} else {
if(flock(fd,LOCK_EX)==0){
printf("pid(%d) %s",getpid(), "the file was locked by parent .\n");
puts( "parent sleep now ..." );
sleep( 10 );
write(fd, "parent\n",strlen("parent\n"));
if(flock(fd,LOCK_UN)==0){
puts("parent the file was unlocked .\n");
}
}
puts( "parent exit..." );
close( fd );
}
return 0;
}
执行结果
[iyunv@centos]# ./slockc
pid(1516) the file was locked by parent .
parent sleep now ...
parent the file was unlocked .
parent exit...
[iyunv@centos]# pid(1517) the file was locked by child .
child sleep now ...
child the file was unlocked .
child exit...
最后查看 /dev/shm/test内容
parent
child |