file_lock.h

  
    
#ifndef FILE_LOCK_H_INCLUDE_
#define FILE_LOCK_H_INCLUDE_

#include
< sys / types.h >
#include
< sys / stat.h >
#include
< fcntl.h >
#include
< unistd.h >

class FileLock {
public :

explicit FileLock( int file_des) {
m_file_des
= file_des;
}

FileLock() {
m_file_des
= - 1 ;
}

void attach( int fd) {
m_file_des
= fd;
}

bool open( char const * file_name) {
if (m_file_des >= 0 ) {
::close(m_file_des);
}

m_file_des
= ::open(file_name, O_CREAT | O_RDWR, 0664 );
return m_file_des >= 0 ;
}

bool lock () {
return lock_reg(m_file_des, F_SETLKW, F_WRLCK, 0 , SEEK_SET, 0 ) >= 0 ;

}

bool try_lock(){
return lock_reg(m_file_des, F_SETLK, F_WRLCK, 0 , SEEK_SET, 0 ) >= 0 ;
}

bool unlock() {
return lock_reg(m_file_des, F_SETLK, F_UNLCK, 0 , SEEK_SET, 0 ) >= 0 ;
}

bool close() {
if (m_file_des >= 0 ) ::close(m_file_des);
m_file_des
= - 1 ;
return true ;
}

~ FileLock() {
}

int m_file_des;
private :
FileLock(FileLock
const & );
FileLock
& operator = (FileLock const & );

int lock_reg( int fd, int cmd, int type, off_t offset, int whence, off_t len) {
if (fd < 0 ) {
return - 1 ;
}

struct flock lock ;
lock .l_type = type;
lock .l_start = offset;
lock .l_whence = whence;
lock .l_len = len;
return fcntl(fd, cmd, & lock );
}
};

#endif // FILE_LOCK_H_INCLUDE_

你可能感兴趣的:(File)