동일한 파일에 동시 액세스 할 수 있고 파일 잠금을 구현하고자하는 두 개의 프로세스가 있습니다. 문제는 하나의 프로세스가 C로 작성되었고 다른 프로세스는 C로 작성되었으며 자바 측에서 어떻게 저수준 잠금이 구현되는지는 분명하지 않다. 플랫폼은 Solaris 10입니다. C 프로세스가 파일을 읽는 동안 Java 프로세스가 업데이트를 수행하지 못하도록 파일 잠금을 도입하려고했습니다. 내 아이디어는 Java 코드에서 10 번 잠금을 획득하려고 시도하고 나서 파일에 무조건 쓰기 만했습니다 (잠금 유형이 권고 잠금이라고 가정). 그러나 java tryLock()은 두 번째 시도에서 C 프로세스의 잠금을 중단하고 읽기를 손상시킵니다.FileChannel tryLock() 메서드는 잠금을 확인하거나 방금 중단합니다.
fd = open(filename, O_RDONLY);
.....
lck.l_type = F_RDLCK;/* F_RDLCK setting a shared or read lock */
lck.l_whence = 0; /* offset l_start from beginning of file */
lck.l_start = 0LL;
lck.l_len = 0LL; /* until the end of the file address space */
....
while( fcntl(fd, F_SETLK64, &lck) < 0){
if(errno == EAGAIN)
....
else if (errno == EIO)
...
else if(errno == ENOLCK)
...
else if (errno == EDEADLK)
...
if(++ii == 10){
break;
}
...
sleep(1);
}
MyLongLastingRead();
...
lck.l_type = F_UNLCK;
fcntl(fd, F_SETLK, &lck);
close(fd);
이 tryLock()
정말 잠금 장치를 확인 하는가 :
int iAttemptCnt = 0;
FileChannel wchannel = new FileOutputStream(new File(fileName), false).getChannel();;
FileLock flock;
while(true){
try{
MyLog.log(MyLog.LVL_INFO, "attempt to lock file");
if((flock = wChannel.tryLock()) == null){
// lock held by another program
if(++iAttemptCnt >= 10
break;
}
else{
MyLog.log(MyLog.LVL_INFO, " file locked");
break;
}
}catch(OverlappingFileLockException ofle){
.......
if(++iAttemptCnt >= 10){
...
break;
}
}catch(IOException ioe){
throw new IOException("failed to lock the file");
}
try{
MyLog.log(MyLog.LVL_INFO, "File already locked, retrying in one second");
Thread.sleep(1000);
}catch(InterruptedException ie){
.....
}
}
C 코드는 fcntl을 사용하여 여기에
단순화 코드 (자바)인가?
불행히도 도움이되지 않았습니다. 어쨌든, 답변 주셔서 감사합니다. – homerski