Is there a good way to detect a stale NFS mount

后端 未结 7 1158
别跟我提以往
别跟我提以往 2020-12-23 15:08

I have a procedure I want to initiate only if several tests complete successfully.

One test I need is that all of my NFS mounts are alive and well.

Can I do

7条回答
  •  我在风中等你
    2020-12-23 15:24

    Writing a C program that checks for ESTALE is a good option if you don't mind waiting for the command to finish because of the stale file system. If you want to implement a "timeout" option the best way I've found to implement it (in a C program) is to fork a child process that tries to open the file. You then check if the child process has finished reading a file successfully in the filesystem within an allocated amount of time.

    Here is a small proof of concept C program to do this:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    
    void readFile();
    void waitForChild(int pid);
    
    
    int main(int argc, char *argv[])
    {
      int pid;
    
      pid = fork();
    
      if(pid == 0) {
        // Child process.
        readFile();
      }
      else if(pid > 0) {
        // Parent process.
        waitForChild(pid);
      }
      else {
        // Error
        perror("Fork");
        exit(1);
      }
    
      return 0;
    }
    
    void waitForChild(int child_pid)
    {
      int timeout = 2; // 2 seconds timeout.
      int status;
      int pid;
    
      while(timeout != 0) {
        pid = waitpid(child_pid, &status, WNOHANG);
        if(pid == 0) {
          // Still waiting for a child.
          sleep(1);
          timeout--;
        }
        else if(pid == -1) {
          // Error
          perror("waitpid()");
          exit(1);
        }
        else {
          // The child exited.
          if(WIFEXITED(status)) {
            // Child was able to call exit().
            if(WEXITSTATUS(status) == 0) {
              printf("File read successfully!\n");
              return;
            }
          }
          printf("File NOT read successfully.\n");
          return;
        }
      }
    
      // The child did not finish and the timeout was hit.
      kill(child_pid, 9);
      printf("Timeout reading the file!\n");
    }
    
    void readFile()
    {
      int fd;
    
      fd = open("/path/to/a/file", O_RDWR);
      if(fd == -1) {
        // Error
        perror("open()");
        exit(1);
      }
      else {
        close(fd);
        exit(0);
      }
    }
    

提交回复
热议问题