#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( "加锁成功 " ); printf( "输入任意字符解锁 " ); getchar(); lock.l_type = F_UNLCK; if ( fcntl( fd, F_SETLK, &lock ) == -1 ) { printf( "释放锁失败 " ); }else{ printf( "释放锁成功 " ); } } return 0; }