#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)}
posted on 2009-10-31 11:50 Len3d 阅读( ...) 评论( ...) 编辑 收藏转载于:https://www.cnblogs.com/len3d/archive/2009/10/31/1593446.html