|
#include <stdio.h>
#include <strings.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#define read_lock(fd, offset, whence, len) reglck((fd), F_SETLKW, F_RDLCK, (offset), (whence), (len))
#define write_lock(fd,offset, whence, len) reglck((fd), F_SETLKW, F_WRLCK, (offset), (whence), (len))
#define un_lock( fd ,offset, whence, len) reglck((fd), F_SETLKW, F_UNLCK, (offset), (whence), (len))
reglck(int fd, int cmd, int type, off_t offset, int whence, off_t len)
{
int ret;
struct flock lock;
lock.l_type = type;
lock.l_start = offset;
lock.l_whence = whence;
lock.l_len = len;
if(cmd == F_GETLK)
{
ret=fcntl(fd, cmd, &lock);
if (lock.l_type == F_WRLCK) printf("child: the text be locked.\n");
if (lock.l_type == F_UNLCK) printf("child: the text no lock.\n");
else printf("process %d set the lock\n", lock.l_pid);
return ret;
}
return (fcntl(fd, cmd, &lock));
}
int main(int argc, char *argv[])
{
int fd;
int retnum;
int pid;
if ((fd=open("./a.c", O_RDWR)) <= 0)
printf("open error!\n");
if(reglck(fd, F_SETLK, F_WRLCK, 0, SEEK_SET, 0)<0)
printf("fcntl error!");
printf("parente pid is %d\n", getpid());
if ( (pid=fork()) < 0 )
printf("fork error");
if (pid == 0)
{ //child
printf("child pid is %d\n",getpid());
if(reglck(fd, F_GETLK, F_WRLCK, 0, SEEK_SET, 0)<0)
printf("in the child fcntl error!");
if ( (retnum=write(fd, argv[1], 6)) < 0 )
printf("child write error!");
printf("%d\n\n", retnum);
close(fd);
exit(0);
}
wait();
un_lock(fd, 0, SEEK_SET, 0);
close(fd);
exit(0);
}
运行程序后:
[root@localhost source]# ./lock hhhhhh;cat a.c
parente pid is 3692
child pid is 3693
child: the text be locked.
process 3692 set the lock
6
hhhhhh@
子进程还是可以修改文件。 |
|