我的程序是父,子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 ) 这个判断中会退出。而实际运行却发现程序继续运行了下去,并加了写锁。
按我的预期是,父进程在 if ( fl.l_type != F_UNLCK ) 这个判断中会退出
自己粗心导致的错误,子进程F_GETLK后,type类型变为UNLCK,(这里在F_SETLK前要再次设置为F_WRLCK),CSDN不知道怎么关闭问题,自己粗心闹了个笑话