1.源码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
int main()
{
FILE *fp = NULL;
int i = 20;
if((fp=fopen("./file.lock", "rb")) == NULL)
{
printf("file open error!\n");
return -1;
}
/*给该文件加锁*/
if(flock(fp->_fileno, LOCK_EX) != 0)
{
printf("file lock by others!\n");
fclose(fp);
return -1;
}
/*加锁时间为20s*/
while(i)
{
printf("sleep %d\n", i--);
sleep(1);
}
flock(fp->_fileno, LOCK_UN);
fclose(fp);
return 0;
}
2.编译源码
$ gcc -o file-1 file.c
$ gcc -o file-2 file.c
3.运行及其结果
$ ./file-1
$ ./file-2
sleep 20
sleep 19
sleep 18
sleep 17
sleep 16
sleep 15
sleep 14
sleep 13
sleep 12
sleep 11
sleep 10
sleep 9
sleep 8
sleep 7
sleep 6
sleep 5
sleep 4
sleep 3
sleep 2
sleep 1
sleep 20
sleep 19
sleep 18
sleep 17
sleep 16
sleep 15
sleep 14
sleep 13
sleep 12
sleep 11
sleep 10
sleep 9
sleep 8
sleep 7
sleep 6
sleep 5
sleep 4
sleep 3
sleep 2
sleep 1
网友评论