C program to implement file locking in a process
####################################################################
PROGRAM 1
####################################################################
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
/* l_type l_whence l_start l_len
l_pid */
struct flock fl = {F_WRLCK, SEEK_SET,
0, 0, 0 };
int fd;
fl.l_pid = getpid();
if (argc > 1)
fl.l_type = F_RDLCK;
if ((fd = open("lockdemo.c", O_RDWR)) ==
-1) {
perror("open");
exit(1);
}
printf("Press <RETURN> to try to get
lock: ");
getchar();
printf("Trying to get lock...");
if (fcntl(fd, F_SETLKW, &fl) == -1) {
perror("fcntl");
exit(1);
}
printf("got lock\n");
printf("Press <RETURN> to release lock:
");
getchar();
fl.l_type = F_UNLCK; /* set to unlock same
region */
if (fcntl(fd, F_SETLK, &fl) == -1) {
perror("fcntl");
exit(1);
}
printf("Unlocked.\n");
close(fd);
return 0;
}
####################################################################
PROGRAM 2
####################################################################
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int lock_file(char *fname)
{
struct flock f;
int fd;
fd = open( fname, O_RDWR );
if( fd == -1 ) {
//printf("Failed to open
%s",fname); /* error handling */
return fd;
}
f.l_type = F_WRLCK;
f.l_start = 0;
f.l_whence = SEEK_SET;
f.l_len = 0;
return fcntl( fd, F_SETLK, &f );
}
int unlock_file(char *fname)
{
struct flock f;
int fd;
fd = open( fname, O_RDWR );
if( fd == -1 ) {
//printf("Failed to open
%s",fname); /* error handling */
return fd;
}
f.l_type = F_UNLCK;
f.l_start = 0;
f.l_whence = SEEK_SET;
f.l_len = 0;
return fcntl( fd, F_SETLK, &f );
}
int add_record( )
{
getchar();
}
int main()
{
int state = 1;
char filename[]="test.lock";
while(state != 0)
state = lock_file(filename);
add_record();
unlock_file(filename);
return 0;
}