linux进程间通信文件锁fcntl函数用法实例

本文通过实例详细介绍了Linux系统中,使用fcntl函数进行进程间通信的文件锁操作,包括写进程的文件加锁、清空、写入及解锁流程,以及读进程的文件加读锁、读取、解锁过程。强调了文件锁在并发读写中的作用,并指出写进程不能以O_TRUNC模式打开文件。
摘要由CSDN通过智能技术生成

linux进程间通信文件锁fcntl函数用法实例

linux系统函数open打开激光数据文件.
write函数写激光数据文件前,给文件加写锁.
read函数读激光数据文件前,给文件加读锁.
1.文件锁流程
write进程:
(1)打开文件
(2)获得文件写锁
(3)清空文件原有内容
(4)移动文件指针到文件开头
(5)写文件
(6)释放文件写锁
(7)关闭文件
read进程:
(1)打开文件
(2)获得文件读锁
(3)写文件
(4)释放文件读锁
(5)关闭文件
读写进程并发,文件打开后才能尝试去给文件加锁,而且该文件锁为建议锁。因此,写进程不能以O_TRUNC模式打开。
2.fileoperation.h
头文件

#include <fstream>
#include <iostream>
#include <vector>
#include <sys/stat.h>
#include <sys/types.h>
#include <cstddef>
#include <stdlib.h> 
#include <math.h>
#include "micros_common_msg/micros_LaserScan.h"
#include "micros_common_msg/micros_OccupancyGrid.h"
#include "micros_common_msg/micros_Path.h"
#include "msg/filepath.h"
#include "time.h"
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sstream>
#define BUFSIZE 64

函数声明

std::string getValue(const char *err_string, int &offset); // get value from buf
void lockSet(int fd, int type); // linux fcntl file lock
bool readTXTL( micros_seq_msg::FilePath &file_path, micros_bt_msg::sensor_msgs::LaserScan &ls, bool usetime = false );
bool writeTXTL( micros_seq_msg::FilePath &file_path, micros_bt_msg::sensor_msgs::LaserScan &ls);

3.fileoperation.cpp
函数实现

std::string MessageFileOperation::getValue(const char *buf, int &offset)
    {
   
for(offset = 0; offset < BUFSIZE; offset++) 
    {
   
        if(buf[offset] == '\0') // 文件末尾
        {
   
            return 0;
        }
        if(buf[offset] == ' ') // 分隔符
        {
   
            if(offset == 0)
            {
   
                if(value.size() > 0) // 边界
                {
   
                    return 0;
                }else 
                
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值