QQ登录

只需一步,快速开始

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 2039|回复: 0

怪问题,居然上不了锁

[复制链接]
发表于 2007-8-14 16:53:29 | 显示全部楼层 |阅读模式
#include <stdio.h>
#include <strings.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

reglck(int fd, int cmd, int type, off_t offset, int whence, off_t len)
{
        struct flock lock;
        lock.l_type=type;
        lock.l_start=offset;
        lock.l_whence=whence;
        lock.l_len=len;
        return (fcntl(fd,cmd,&lock));
}

int main(int argc, char *argv[])
{
        int fd,i;
        int pid;
        if((fd=open("./a.c",O_RDWR))<=0)
                printf("open error!\n");

        if(reglck(fd,F_SETLKW,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());
                struct flock flk;
                bzero(&flk,sizeof(struct flock));
                flk.l_type=F_RDLCK;
                flk.l_start=0;
                flk.l_whence=SEEK_SET;
                flk.l_len=0;
                fcntl(fd,F_GETLK,&flk);
                if(flk.l_type==F_WRLCK) printf("child: the text be locked.\n");
                if(flk.l_type==F_UNLCK) printf("child: the text no lock.\n");
                else printf("process %d set the lock\n",flk.l_pid);

                if((i=write(fd,argv[1],6))<0) printf("child write error!");
                printf("%d\n\n",i);
                close(fd);
                exit(0);
        }
        waitpid(pid,NULL,0);
        close(fd);
        exit(0);
}


运行程序后:
[root@localhost source]# ./lock chenli;cat a.c
parente pid is 6070
child pid is 6071
child: the text be locked.
process 6070 set the lock
6

chenli@
子进程还是可以修改文件。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

GMT+8, 2024-3-29 19:27 , Processed in 0.149573 second(s), 15 queries .

© 2021 Powered by Discuz! X3.5.

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