5
我有兩個進程可以訪問相同的文件一致,並希望實現文件鎖定。麻煩似乎是一個進程是用java編寫的,另一個是用C編寫的,並且不清楚在java端如何實現低級別鎖定。該平臺是Solaris 10.我試圖在文件上引入鎖定,以防止在C進程正在讀取文件時更新由Java進程完成。我的想法是試圖從Java代碼中獲取一次鎖定10次,然後才能無條件地寫入文件(我認爲鎖定類型是一個顧問鎖定)。然而,java tryLock()在第二次嘗試時破壞了C進程的鎖定並破壞了讀取。FileChannel tryLock()方法檢查鎖定還是將它們打斷?
下面是代碼,簡化(JAVA):
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:
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()
檢查鎖?
不幸的是,它並沒有幫助。無論如何,謝謝你的答案。 – homerski