本文转载自:http://blog.csdn.net/fansongy/article/details/6853395
一、文件锁
文件锁用于多个用户共同使用或操作同一个文件。有读锁的时候可以再加读锁,不能再加写锁。有写锁的时候,不能加任何锁,加读锁时,该描述符必须是读打开,加写锁时,该描述符必须是写打开,且只在进程间有用。
重写的上锁方法
[cpp] view plain copy print?
//lock.c
int lock_set(int fd,int type){
struct flock lock;
lock.l_type=type;
lock.l_start=0;
lock.l_whence=SEEK_SET;
lock.l_len = 0;
lock.l_pid=-1;
fcntl(fd,F_GETLK,&lock);
if(lock.l_type!=F_UNLCK){
if(lock.l_type == F_RDLCK)
printf("Read lock already set by %d!\n",lock.l_pid);
else if(lock.l_type == F_WRLCK)
printf("Write lock already set by %d!\n",lock.l_pid);
}
lock.l_type = type;
//此处的F_SETLKW为F_SETLK的阻塞版本,当无法获取锁时进入睡眠等待状态
if(fcntl(fd,F_SETLKW,&lock)
#include
#include
#include"lock.c"
int main(){
int fd;
fd=open("readme",O_RDWR|O_CREAT,0666);
if(fd
#include
#include
#include"lock.c"
int main(){
int fd;
fd=open("readme",O_RDWR|O_CREAT,0666);
if(fd
#include
#include
#include
#define MAX(a,b) (a>b?a:b)
int main(){
int fd[3];
char buff[1024];
int res,max_fd,i,num;
fd_set insert,temp_insert;
struct timeval tv;
fd[0]=0;
if((fd[1]=open("in1",O_RDONLY|O_NONBLOCK))
#include
#include
#include
#include
#include
#include
#define MAX_BUFFER_SIZE 1024
#define IO_IN_FILES 3
#define TIME_DELAY 60000
int main() {
struct pollfd fds[IO_IN_FILES];
char buff[MAX_BUFFER_SIZE];
int i,res,real_read;
fds[0].fd=0;
if((fds[1].fd=open("in1",O_RDONLY|O_NONBLOCK))