上一个最开始写的程序吧,简单,就是两个进程互斥访问文件。
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
void readfile(FILE*fd);
void writefile(FILE*fd);
int lock_file(int fd,int cmd,int type,off_t offset,int whence,off_t len);
using namespace std;
int main()
{
FILE* fd;
//fd=fopen("./test_file","a+");
if(fork()>0)
{
writefile(fd);
}else
{
readfile(fd);
}
fclose(fd);
}
void fileop1(FILE* fd)
{
while(lock_file(fileno(fd),F_SETLK,F_WRLCK,0,SEEK_SET,0)<0)
{
sleep(1);
perror("FILEOP1 TRY LOCK");
}
cout<<"fileop1 locked"<<endl;
sleep(5);
if (lock_file(fileno(fd),F_SETLK,F_UNLCK,0,SEEK_SET,0)<0)
{
perror("UNLOCK FAILED");
}
}
void fileop2(FILE* fd)
{
while(lock_file(fileno(fd),F_SETLK,F_WRLCK,0,SEEK_SET,0)<0)
{
sleep(1);
perror("FILEOP2 TRY LOCK");
}
cout<<"fileop2 locked"<<endl;
sleep(5);
if (lock_file(fileno(fd),F_SETLK,F_UNLCK,0,SEEK_SET,0)<0)
{
perror("UNLOCK FAILED");
}
}
int lock_file(int fd,int cmd,int type,off_t offset,int whence,off_t len)
{
struct flock lock;
lock.l_type=type;
lock.l_start=offset;
lock.l_whence=whence;
lock.l_len=len;
return(fcntl(fd,cmd,&lock));
//if(lock_file(LockFD,F_SETLK,F_WRLCK,0,SEEK_SET,0)
}