linux編程fcntl獲取和設置文件鎖

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


#define ERR_EXIT( m ) \
        do \
        { \
                perror( m ); \
                exit( EXIT_FAILURE ); \
        }while( 0 )


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

        if( argc != 2 ) {
                fprintf( stderr, "usage:%s filename", argv[0] );
                exit( EXIT_FAILURE );
        }

        int fd;
        fd = open( argv[1], O_RDWR | O_TRUNC | O_CREAT, 0666 );
        if( -1 == fd ) {
                ERR_EXIT( "文件打開失敗" );
        }

        struct flock lock;
        memset( &lock, 0, sizeof( lock ) );

        lock.l_type = F_WRLCK; //寫鎖
        lock.l_whence = SEEK_SET;
        lock.l_start = 0;
        lock.l_len = 0;


        //加文件寫鎖, 另外一個進程操做文件 直接報錯
        //int ret = fcntl( fd, F_SETLK, &lock );
        //加文件寫鎖, 另外一個進程操做文件 會等待這個進程釋放鎖
        int ret = fcntl( fd, F_SETLKW, &lock );
        if( -1 == ret ) {
                ERR_EXIT( "加鎖失敗" );
        }else {
                printf( "加鎖成功\n" );
                printf( "輸入任意字符解鎖\n" );
                getchar();
                lock.l_type = F_UNLCK;
                if ( fcntl( fd, F_SETLK, &lock ) == -1 ) {
                        printf( "釋放鎖失敗\n" );
                }else{
                        printf( "釋放鎖成功\n" );
                }
        }

        return 0;
}
相關文章
相關標籤/搜索