APUE习题14.1

#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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值