69,371
社区成员
发帖
与我相关
我的任务
分享
/*
============================================================================
Name : FileContentLockTest.c
Author : test
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
static const char *test_file = "/home/lock_content.txt";
static void show_lock_info(struct flock *to_show);
#define SIZE_TO_TRY 5
int main(void) {
setbuf(stdout, NULL);
setbuf(stderr, NULL);
int file_desc;
int res;
struct flock region_to_test;
int start_byte;
file_desc = open(test_file, O_RDWR | O_CREAT, 0666);
if(!file_desc) {
fprintf(stderr, "Uable to open %s for read and write\n", test_file);
printf("%d", errno);
exit(EXIT_FAILURE);
}
for(start_byte = 0; start_byte < 99; start_byte += SIZE_TO_TRY) {
region_to_test.l_type = F_WRLCK;
region_to_test.l_whence = SEEK_SET;
region_to_test.l_start = start_byte;
region_to_test.l_len = SIZE_TO_TRY;
region_to_test.l_pid = -1;
printf("Testing F_WRCLK on regon for %d to %d\n",
start_byte, start_byte + SIZE_TO_TRY);
res = fcntl(file_desc, F_GETLK, ®ion_to_test);
if(res == -1) {
fprintf(stderr, "F_GETLK failed\n");
exit(EXIT_FAILURE);
}
if(region_to_test.l_pid != -1) {
printf("Lock would fail. F_GETLK returned:\n");
show_lock_info(®ion_to_test);
}
else {
printf("F_WRLCK - Lock would succeed\n");
}
/**共享锁**/
region_to_test.l_type = F_RDLCK;
region_to_test.l_whence = SEEK_SET;
region_to_test.l_start = start_byte;
region_to_test.l_len = SIZE_TO_TRY;
region_to_test.l_pid = -1;
printf("Testing F_WRCLK on regon for %d to %d\n",
start_byte, start_byte + SIZE_TO_TRY);
res = fcntl(file_desc, F_GETLK, ®ion_to_test);
if(res == -1) {
fprintf(stderr, "F_GETLK failed\n");
exit(EXIT_FAILURE);
}
if(region_to_test.l_pid != -1) {
printf("Lock would fail. F_GETLK returned:\n");
show_lock_info(®ion_to_test);
}
else {
printf("F_RDLCK - Lock would succeed\n");
}
}
close(file_desc);
exit(EXIT_SUCCESS);
}
void show_lock_info(struct flock *to_show) {
printf("\tl_type %d, ", to_show->l_type);
printf("l_whence %d, ", to_show->l_whence);
printf("l_start %ld, ", to_show->l_start);
printf("l_len %ld, ", to_show->l_start);
}