NAME
fcntl - manipulate file descriptor
SYNOPSIS
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd, ... /* arg */ );
DESCRIPTION
fcntl() performs one of the operations described below on the open file
descriptor fd. The operation is determined by cmd.
#include<stdio.h> #include<fcntl.h> #include<stdlib.h> #include<unistd.h> #include<string.h> #define FILE_NAME "flock.txt" int set_lock(const int fd,const int type){ printf("pid: %d\n",getpid()); struct flock fflock; memset(&fflock ,0,sizeof(struct flock)); fcntl(fd,F_GETLK,&fflock); if(fflock.l_type!=F_UNLCK){ if(fflock.l_type==F_RDLCK){ printf("flock has been set to read lock by %d\n",fflock.l_pid); }else if(fflock.l_type==F_WRLCK){ printf("flock has been set to write lock by %d\n",fflock.l_pid); } } fflock.l_type=type; fflock.l_whence=SEEK_SET; fflock.l_start=0; fflock.l_len=0; fflock.l_pid=-1; if(fcntl(fd,F_SETLKW,&fflock)<0){ printf("set lock failed\n"); return -1; } switch(fflock.l_type){ case F_RDLCK: printf("read lock is set by %d\n",getpid()); break; case F_WRLCK: printf("read lock is set by %d\n",getpid()); break; case F_UNLCK: printf("read lock is set by %d\n",getpid()); break; } printf("Process pid =%d out. \n",getpid()); return 0; } int main(void){ int fd=open(FILE_NAME,O_RDWR|O_CREAT,0666); if(fd<0){ printf("file: %s open failed!!!\n",FILE_NAME); exit(-1); } //lock set_lock(fd,F_WRLCK);//对文件上写锁 getchar(); //unlock set_lock(fd,F_UNLCK);//解锁 getchar(); return 0; }
对上述代码进行参数修改(F_RDLCK,F_WRLCK,F_UNLCK)可观察不同文件锁的权限影响.
结论:当对文件上写锁后,则不可以再对文件写或读.
当对文件上读锁后,则不可以再对文件写,但可以读.