Nfs

使用 NFSv4 失敗的群

  • July 12, 2021

我不知道為什麼這段程式碼不能在 NFS4 下執行,使用 NFS3 可以完美執行。這個想法是避免在程序仍在讀取文件時寫入文件。

我想調試,但我們的系統管理員無法調試。這可能是原因。在我們的 NFS4 安裝下,我總是會遇到這種情況

 if ( flock(fp,LOCK_EX) == -1)
   printf("Error: file %s is already locked\n", fileName);

整個程序是:

#include <sys/file.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv){

   if (argc<2){
       printf("Usage:\n a.out fileName\n");
       return 1;
   }

   char *fileName=argv[1];
   int  fp;
    
   /* block the file, I know a process can write 
   rendering my information useless*/
   fp=open(fileName,O_RDONLY);

   if ( flock(fp,LOCK_EX) == -1){
       printf("Error: file %s is already locked\n", fileName);
   }
   else{
       printf("OK: file %s was locked\n",fileName );
   }

   /* read and parse the fileName 
      another process should not be able to write or
      modify the fileName while I am reading it
   */
   return 0;    
}

編輯:我想澄清一下。這是我正在使用的程式碼片段。fileName 應該是一個有效的現有文件

我正在閱讀文件名並製作副本,編輯一些部分。我知道,當我這樣做時,外部程序可以更新文件名。我想使用信號量來避免修改這個文件,直到我完成它。該程序執行良好,直到停止這樣做。唯一的區別是文件名所在的文件系統。它從 NFS3 更新到 NFS4。甚至作業系統 (SLE15.2) 與核心 5.3.18 相同,並且使用 strerror(errno) 在 NFS4 上產生 seg 錯誤。我做 print("%d",error) 時的唯一提示是 9 應該是“錯誤的文件描述符”

謝謝你的幫助

朱莉婭

我剛剛檢查了flock的聯機幫助頁,在NOTES部分是重要的部分:

NFS details
  In Linux kernels up to 2.6.11, flock() does not lock files over NFS (i.e., the scope of locks was limited to the local system).  Instead, one could use fcntl(2) byte-range locking, which does
  work over NFS, given a sufficiently recent version of Linux and a server which supports locking.

  Since Linux 2.6.12, NFS clients support flock() locks by emulating them as fcntl(2) byte-range locks on the entire file.  This means that fcntl(2) and  flock()  locks  do  interact  with  one
  another over NFS.  It also means that in order to place an exclusive lock, the file must be opened for writing.

  Since  Linux  2.6.37,  the  kernel  supports  a compatibility mode that allows flock() locks (and also fcntl(2) byte region locks) to be treated as local; see the discussion of the local_lock
  option in nfs(5).

您只是打開文件進行讀取,這就是群呼叫失敗的原因。

引用自:https://serverfault.com/questions/1069368