Optimal lock file method

后端 未结 6 1406
离开以前
离开以前 2020-11-30 23:25

Windows has an option to open a file with exclusive access rights. Unix doesn\'t.

In order to ensure exclusive access to some file or device, it is common practice

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 00:23

    The answer of Hasturkun is the one that has put me on track.

    Here is the code I use

    #include 
    #include 
    #include 
    #include 
    
    /*! Try to get lock. Return its file descriptor or -1 if failed.
     *
     *  @param lockName Name of file used as lock (i.e. '/var/lock/myLock').
     *  @return File descriptor of lock file, or -1 if failed.
     */
    int tryGetLock( char const *lockName )
    {
        mode_t m = umask( 0 );
        int fd = open( lockName, O_RDWR|O_CREAT, 0666 );
        umask( m );
        if( fd >= 0 && flock( fd, LOCK_EX | LOCK_NB ) < 0 )
        {
            close( fd );
            fd = -1;
        }
        return fd;
    }
    
    /*! Release the lock obtained with tryGetLock( lockName ).
     *
     *  @param fd File descriptor of lock returned by tryGetLock( lockName ).
     *  @param lockName Name of file used as lock (i.e. '/var/lock/myLock').
     */
    void releaseLock( int fd, char const *lockName )
    {
        if( fd < 0 )
            return;
        remove( lockName );
        close( fd );
    }
    

提交回复
热议问题