| 
 | 
 
#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@ 
子进程还是可以修改文件。 |   
 
 
 
 |