How not to open a file twice in linux?

后端 未结 3 1014
挽巷
挽巷 2021-01-21 18:24

I have a linked list with an fd and a string I used to open this file in each entry. I want to open and add files to this list only if this file is not already opened, because I

3条回答
  •  旧时难觅i
    2021-01-21 19:05

    As long as you don't close the successfully and intentionally opened files, you can use nonblocking flock to prevent another lock on the same file:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int openAndLock(const char* fn){
      int fd = -1;
      if(((fd = open(fn, O_RDONLY)) >= 0) && (flock(fd, LOCK_EX|LOCK_NB) == 0)){
          fprintf(stderr, "Successfully opened and locked %s\n", fn);
          return fd;
      }else{
        fprintf(stderr, "Failed to open or lock %s\n", fn);
        close(fd);
        return -1;
      }
    }
    
    int main(int argc, char** argv){
      for(int i=1; i

    Example:

    $ touch foo
    $ ln foo bar
    $ ./a.out foo foo
    Successfully opened and locked foo
    Failed to open or lock foo
    $ ./a.out foo bar
    Successfully opened and locked foo
    Failed to open or lock bar
    

提交回复
热议问题