首页 新闻 会员 周边 捐助

APUE记录锁问题

0
悬赏园豆:50 [已关闭问题] 关闭于 2015-12-29 13:49

  我的程序是父,子2个进程尝试对一个打开的文件的同一区域加写锁。先让子进程获得锁,然后再让父进程去锁。按正常的运行,应该是父进程测试锁时会发现已有一个排斥它的锁存在,但是实际程序运行却发现父进程会发现可以加锁。代码如下:

 1 void pflock(struct flock *fl)
 2 {
 3     printf("fl.l_type:%d,fl.l_whence::%d,fl.l_start:%d,fl.l_len:%d,fl.l_pid:%lu\n",fl->l_type,fl->l_whence,fl->l_start,fl->l_len,(long)fl->l_pid);
 4 }
 5 int main(void)
 6 {
 7     int fd, ret;
 8     pid_t pid;
 9     struct flock fl;
10     
11     fd = open("./d", O_RDWR);
12     if ( fd < 0 )
13     {
14         perror("open");
15         return -1;
16     }
17 
18     pid = fork();
19     if ( pid < 0 )
20     {
21         perror("fork");
22         close(fd);
23         return -1;
24     }
25     else if ( pid == 0 )
26     {
27         printf("child pid:%lu\n",(long)getpid());
28         fl.l_type = F_WRLCK;
29         fl.l_whence = SEEK_SET;
30         fl.l_start = 1;
31         fl.l_len = 2;
32         fl.l_pid = getpid();
33         
34         ret = fcntl(fd, F_GETLK, &fl);
35         if ( fl.l_type != F_UNLCK )
36         {
37             printf("already have a file lock\n");
38             pflock(&fl);
39             close(fd);
40             exit(0);
41         }
42 
43         printf("child set flock\n");
44         ret = fcntl(fd, F_SETLK, &fl);
45         if ( ret < 0 )
46         {
47             perror("fcntl");
48             close(fd);
49             exit(0);
50         }
51         while(1);
52     }
53     else
54     {
55         printf("parent pid:%lu\n",(long)getpid());
56         sleep(1);   //let child process get a flock before parents
57         
58         fl.l_type = F_WRLCK;
59         fl.l_whence = SEEK_SET;
60         fl.l_start = 1;
61         fl.l_len = 2;
62         fl.l_pid = getpid();
63         
64         ret = fcntl(fd, F_GETLK, &fl);
65         if ( fl.l_type != F_UNLCK )
66         {
67             printf("already have a file lock\n");
68             pflock(&fl);
69             close(fd);
70             exit(0);
71         }
72         
73         printf("parent set flock\n");
74         ret = fcntl(fd, F_SETLK, &fl);
75         if ( ret < 0 )
76         {
77             perror("fcntl");
78             close(fd);
79             exit(0);
80         }
81         while(1);
82     }
83 
84     close(fd);
85     exit(0);
86 }
View Code

  按我的预期是,父进程在 if ( fl.l_type != F_UNLCK ) 这个判断中会退出。而实际运行却发现程序继续运行了下去,并加了写锁。

thammer的主页 thammer | 初学一级 | 园豆:148
提问于:2015-12-29 13:17
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册