- 論壇徽章:
- 0
|
我的程序是父,子2個(gè)進(jìn)程嘗試對(duì)一個(gè)打開的文件的同一區(qū)域加寫鎖。先讓子進(jìn)程獲得鎖,然后再讓父進(jìn)程去鎖。按正常的運(yùn)行,應(yīng)該是父進(jìn)程測(cè)試鎖時(shí)會(huì)發(fā)現(xiàn)已有一個(gè)排斥它的鎖存在,但是實(shí)際程序運(yùn)行卻發(fā)現(xiàn)父進(jìn)程會(huì)發(fā)現(xiàn)可以加鎖。代碼如下:- 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);
- }
復(fù)制代碼 按我的預(yù)期是,父進(jìn)程在 if ( fl.l_type != F_UNLCK ) 這個(gè)判斷中會(huì)退出。而實(shí)際運(yùn)行卻發(fā)現(xiàn)程序繼續(xù)運(yùn)行了下去,并加了寫鎖。 |
|