1、实验代码
flock_demo.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>
#include <errno.h>
int main (void)
{
int fd, i;
char filename[] = "data.log";
extern int errno;
fd = open (filename, O_WRONLY | O_CREAT, 0666);
if (fd != -1)
{
printf ("open file %s success \n", filename);
printf ("pls input a num to lock the file.\n");
scanf ("%d", &i);
printf ("try to lock the file...\n");
if (flock (fd, LOCK_EX) == 0)
printf ("lock file success\n");
else
printf ("lock file failed\n");
write (fd, "hello", 5);
printf ("input a num to Unlock the file.\n");
scanf ("%d", &i);
if (flock (fd, LOCK_UN) == 0)
printf ("file unlock success\n");
else
printf ("file unlock failed\n");
while (1);
}
else
{
perror ("open");
exit (EXIT_FAILURE);
}
return 0;
}
执行结果:
fcntl.c
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main (int argc, char *argv[])
{
if (argc > 1)
{
int fd = open (argv[1], O_WRONLY | O_CREAT, 0666);
if (fd == -1)
{
perror ("open");
exit (-1);
}
static struct flock lock;
lock.l_type = F_WRLCK;
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
lock.l_pid = getpid();
printf ("trying lock %s ...\n", argv[1]);
int ret = fcntl (fd, F_SETLKW, &lock);
if (ret == 0)
{
printf ("lock %s succeed\n", argv[1]);
while (1);
}
}
return 0;
}
执行结果:
lockf.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/file.h>
int main (int argc, char *argv[])
{
int fd, ret;
int pid;
fd = open ("tmp.txt", O_RDWR | O_CREAT, 0666);
ret = flock (fd, LOCK_EX);
printf ("flock return ret:%d\n", ret);
ret = lockf (fd, F_LOCK, 0);
printf ("lockf return ret:%d\n", ret);
sleep (30);
return 0;
}
执行结果: