您的位置:首页 > 运维架构 > Linux

linux 记录锁的应用

2013-09-26 11:28 405 查看
//文件加读写锁

#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <unistd.h>

#include <fcntl.h>

#include <errno.h>

#include <string.h>

void my_err(const char *err_string, int line)

{

    fprintf(stderr, "line: %d ", line);

    perror(err_string);

    exit(1);

}

int lock_set(int fd, struct flock *lock)

{

    if(fcntl(fd, F_SETLK, lock) == 0)

    {

        if (lock->l_type == F_RDLCK)

        {

            printf("set read lock, pid:%d\n", getpid());

        }

        else if (lock->l_type == F_WRLCK)

        {

            printf("set write lock, pid:%d\n", getpid());

        }

        else if (lock->l_type == F_UNLCK)

        {

            printf("release lock, pid:%d\n", getpid());

        }

    }

    else

    {

        perror("lock operation fail\n");

        return -1;

    }

    return 0;

}

//测试文件是否枷锁,没有加锁时返回0

int lock_test(int fd, struct flock *lock)

{

    if (fcntl(fd, F_GETLK, lock) == 0)

    {

        if (lock->l_type == F_UNLCK)

        {

            printf("lock can be set in fd\n");

            return 0;

        }

        else

        {

            if (lock->l_type == F_RDLCK)

            {

                printf("read lock has been set by:%d\n", lock->l_pid);

            }

            else if (lock->l_type == F_WRLCK)

            {

                printf("write lock has been set by:%d\n", lock->l_pid);

            }

            return -2;

        }

    }

    else

    {

        perror("get incompatible locks fail");

        return -1;

    }

}

int main(int argc, char *argv[])

{

    int fd;

    int ret;

    struct flock lock;

    char buf[32];

    if ((fd = open("/home/lhl/test/testa/lhl.cpp", O_CREAT | O_TRUNC | O_RDWR, S_IRWXU)) == -1)

    {

        my_err("open", __LINE__);

    }

    if(write(fd, "lihailong111", strlen("lihailong111")) != strlen("lihailong111"))

    {

        my_err("write", __LINE__);

    }

    memset(&lock, 0, sizeof(struct flock));

    memset(buf, 0, sizeof(buf));

    //对整个文件加锁

    lock.l_start = SEEK_SET;

    lock.l_whence = 0;

    lock.l_len = 0;

    //测试文件是否加了读锁

    lock.l_type = F_RDLCK;

    if (lock_test(fd, &lock) == 0)

    {

        //给文件加读锁

        lock.l_type = F_RDLCK;

        lock_set(fd, &lock);

    }

    lseek(fd, 0, SEEK_SET);

    if ((ret = read(fd, buf, sizeof(buf))) < 0)

    {

        my_err("read", __LINE__);

    }

    printf("%s\n", buf);

    getchar();

    //测试文件是否加写锁

    lock.l_type = F_WRLCK;

    if (lock_test(fd, &lock) == 0)

    {

        //给文件加写锁

        lock.l_type = F_WRLCK;

        lock_set(fd, &lock);

    }

    //释放锁

    lock.l_type = F_UNLCK;

    lock_set(fd, &lock);

    close(fd);

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: