直接提供一份文件锁的demo:

复制代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>

/*check lock status*/
void wr_lock_status(int type)
{
    switch (type){
        case F_RDLCK: printf("Current lock is F_RDLCK\n");
                  break;
        case F_WRLCK: printf("Current lock is F_WRLCK\n");
                  break;
        case F_UNLCK: printf("Current lock is F_UNLCK\n");
                  break;
        default: 
                  break;
    }
}

/*lock the file*/
int wr_file_lock(char *filename, int lock_type)
{
    int fd;
    struct flock lock;
    int ret;
    fd = open(filename,O_RDWR | O_TRUNC);
    if (-1 == fd){
        perror("open error\n");
        return -1;
    }
    
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 0;
    lock.l_type = lock_type;
    lock.l_pid = -1;

    ret = fcntl(fd,F_GETLK,&lock);
    if (-1 == ret){
        perror("Get lock status failed\n");
        return -1;
    }
    
    wr_lock_status(lock.l_type);
    //unlck then do it
    if (lock.l_type == F_UNLCK){
        lock.l_type = lock_type;
        ret = fcntl(fd,F_SETLK,&lock);
        if (-1 == ret){
            printf("Lock failed %d\n",lock.l_type);
            return -1;
        }
        wr_lock_status(lock.l_type);
    }else{
        return -1;
    }
    return 0;
}    
/*write something in file*/
int wr_file_write(char *filename, char *text)
{
    FILE *file;
    int ret;
    file = fopen(filename,"ab");
    if (NULL == file){
        perror("error fopen\n");
        return -1;
    }
    ret = fwrite(text,sizeof(char),strlen(text),file);
    if (EOF == ret){
        perror("error fwrite\n");
        return -1;
    }
    return ret;
}


int main(int argc, char **argv)
{
    char filename[32] = "/tmp/wat";
    char text[32] = "helloworld";
    int ret;
    ret = wr_file_lock(filename,F_WRLCK);    
    if (-1 == ret){
        printf("wr_file_lock error at main\n");
        return -1;
    }
    printf("lock wrlock succussfully\n");
    ret = wr_file_write(filename,text);
    if (-1 == ret){
        printf("fwrite failed\n");
        return -1;
    }
    printf("fwrite %d\n",ret);

    //ret = wr_file_lock(filename,F_UNLCK);    
    if (-1 == ret){
        perror("unlock error\n");
        return -1;
    }
    while(1){
        sleep(2);
        ret = wr_file_write(filename,text);
        if (-1 == ret){
            printf("fwrite failed\n");
            return -1;
        }
        printf("fwrite %d\n",ret);
    }
    return 0;
}
复制代码

效果图:

 

 

已经用上F_WRLCK则需要去解锁。