Chinaunix
标题:
APUE记录锁问题
[打印本页]
作者:
tang_m_cong
时间:
2015-12-28 21:48
标题:
APUE记录锁问题
我的程序是父,子2个进程尝试对一个打开的文件的同一区域加写锁。先让子进程获得锁,然后再让父进程去锁。按正常的运行,应该是父进程测试锁时会发现已有一个排斥它的锁存在,但是实际程序运行却发现父进程会发现可以加锁。代码如下:
void pflock(struct flock *fl)
{
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);
}
int main(void)
{
int fd, ret;
pid_t pid;
struct flock fl;
fd = open("./d", O_RDWR);
if ( fd < 0 )
{
perror("open");
return -1;
}
pid = fork();
if ( pid < 0 )
{
perror("fork");
close(fd);
return -1;
}
else if ( pid == 0 )
{
printf("child pid:%lu\n",(long)getpid());
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 1;
fl.l_len = 2;
fl.l_pid = getpid();
ret = fcntl(fd, F_GETLK, &fl);
if ( fl.l_type != F_UNLCK )
{
printf("already have a file lock\n");
pflock(&fl);
close(fd);
exit(0);
}
printf("child set flock\n");
ret = fcntl(fd, F_SETLK, &fl);
if ( ret < 0 )
{
perror("fcntl");
close(fd);
exit(0);
}
while(1);
}
else
{
printf("parent pid:%lu\n",(long)getpid());
sleep(1); //let child process get a flock before parents
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 1;
fl.l_len = 2;
fl.l_pid = getpid();
ret = fcntl(fd, F_GETLK, &fl);
if ( fl.l_type != F_UNLCK )
{
printf("already have a file lock\n");
pflock(&fl);
close(fd);
exit(0);
}
printf("parent set flock\n");
ret = fcntl(fd, F_SETLK, &fl);
if ( ret < 0 )
{
perror("fcntl");
close(fd);
exit(0);
}
while(1);
}
close(fd);
exit(0);
}
复制代码
按我的预期是,父进程在 if ( fl.l_type != F_UNLCK ) 这个判断中会退出。而实际运行却发现程序继续运行了下去,并加了写锁。
作者:
tang_m_cong
时间:
2015-12-29 16:11
问题已解决,是自己粗心导致,子进程测试是否有锁时,type类型被修改为F_UNLCK,设置锁时,忘记将类型重新改回为F_RDLC。
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2