#include<iostream>
#include<apue.h>
#include<my_error.h>
#include<unistd.h>
#include<fcntl.h>
#include<signal.h>
#include<errno.h>
#include<signal.h>
using namespace std;
extern int errno;
struct flock fcntlLock(short type,short whence,off_t start,off_t len,pid_t pid){
struct flock fptr;
//set flock
fptr.l_type=type;
fptr.l_whence=whence;
fptr.l_start=start;//lock from start
fptr.l_len=len;//lock len bytes
fptr.l_pid=pid;
return fptr;
}
void sig_int(int a){
//don't do anything
}
int main(){
int p1,p2,fd;
//open file
if((fd=open("14.1test",O_RDWR|O_CREAT,0666))<0)
err_sys("open error\n");
if((p1=fork())<0)
err_sys("fork error\n");
else if(p1==0){//child1
if(signal(SIGINT,sig_int)==SIG_ERR)
err_sys("signal error");
//child1 set read lock
struct flock flock1=fcntlLock(F_RDLCK,SEEK_SET,0,10,fd);
if(fcntl(fd,F_SETLK,&flock1)<0)
err_sys("child1 fcntl error");
else
cout<<"child1 set read lock"<<endl;
pause();//waiting here
cout<<"child1 exit"<<endl;
exit(0);
}else
sleep(2);//child go first
while((p2=fork())<0);
if(p2==0){//child2
//child2 set write lock,child2 will be blocked
struct flock flock2=fcntlLock(F_WRLCK,SEEK_SET,0,10,fd);
cout<<"child2 try to set write lock"<<endl;
if(fcntl(fd,F_SETLKW,&flock2)<0)
err_sys("child2 fcntl error,blocking...");
else
cout<<"child2 set write lock success"<<endl;
cout<<"child2 returned and got write lock,then exit"<<endl;
exit(0);
}else if(p2<0)
err_sys("second fork error\n");
else
sleep(2);//child go first
//parent set read lock,try to test what will happen.
struct flock flock3=fcntlLock(F_RDLCK,SEEK_SET,0,10,fd);
if(fcntl(fd,F_SETLK,&flock3))
err_sys("parent fcntl error");
else
cout<<"parent set read lock"<<endl;
kill(p1,SIGINT);
flock3=fcntlLock(F_UNLCK,SEEK_SET,0,10,fd);//unlock
if(fcntl(fd,F_SETLK,&flock3))
err_sys("parent second fcntl error");
else
cout<<"parent unlock read lock"<<endl;
}
APUE习题14.1
最新推荐文章于 2021-04-20 22:06:53 发布