LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 803|回复: 2

怪问题,居然上不了锁,高手来看看

[复制链接]
发表于 2007-8-16 09:34:53 | 显示全部楼层 |阅读模式
#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@
子进程还是可以修改文件。
发表于 2007-8-16 10:39:59 | 显示全部楼层
锁,用来房门或者箱子。本意上和摆在地上的一堆东西,然后每个人在每件东西周围画个圈然后写上自己的名字没多少区别。只能防君子,不能防小人。你锁了门,我从窗户里进去还是想干什么干什么。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2007-8-16 15:40:25 | 显示全部楼层
呵呵,诙谐幽默,又有道理,受教了。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表