记录锁

#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <sys/wait.h>
#include <stdlib.h>
using namespace std;

/*
    lockType:F_RDLCK,F_WRLCK,F_UNLCK
*/
int controlFile(int fd,int lockType)
{
    struct flock fileLock;
    fileLock.l_type = lockType;
    fileLock.l_start = 0;
    fileLock.l_whence = SEEK_SET;
    fileLock.l_len = 0;
    return fcntl(fd,F_SETLK,&fileLock);
}

int main()
{
    pid_t pid;

    if((pid=fork())<0)
    {
        return -1;
    }else if(pid==0){
        sleep(3);
        int fd = open("test.txt",O_RDWR | O_CREAT  | O_APPEND);
        int ret = controlFile(fd,F_WRLCK);
        //加锁失败也是可以写的,所以这里需要程序员在加锁的时候去判定是否有别的进程在锁定文件
        if(ret<0){
            cout << "child lock file fail" << endl;
        }else{
            write(fd,"test0",5);
            controlFile(fd,F_UNLCK);
        }
        close(fd);
        exit(0);
    }else
    {
        int fd = open("test.txt",O_RDWR | O_CREAT  | O_APPEND);
        int ret = controlFile(fd,F_WRLCK);
        if(ret<0){
            cout << "parent lock file fail" << endl;
        }else{
            write(fd,"test1",5);
            sleep(10);
            controlFile(fd,F_UNLCK);
        }
        close(fd);
    }
    return 0;
}


child lock file fail

你可能感兴趣的:(记录)