linux下C语言中的flock函数用法

本文介绍了Linux系统中C语言的flock函数,用于对文件进行共享和独占锁操作。flock在打开文件后,可以在读写前加锁,读写后解锁。然而,它不提供锁检查,需要用户在读写前自行检查。一个进程可能只持有文件的一种锁,并且锁与文件描述符相关联,关闭所有副本才能释放。示例代码展示了如何使用flock加锁和解锁,以及潜在的问题:当未检查锁状态直接写入已锁定文件时,可能会导致数据冲突。
摘要由CSDN通过智能技术生成

先贴出来flock在man页下的解释

FLOCK(2)                   Linux Programmer’s Manual                  FLOCK(2)
NAME
       flock - apply or remove an advisory lock on an open file
SYNOPSIS
       #include <sys/file.h>
       int flock(int fd, int operation);
DESCRIPTION
       Apply or remove an advisory lock on the open file specified by fd.  The parameter operation is one of the following:
              LOCK_SH   Place a shared lock.  More than one process may hold a shared lock for a given file at a given time.
              LOCK_EX   Place  an exclusive lock.  Only one process may hold an exclusive lock for a given file at a given time.
              LOCK_UN   Remove an existing lock held by this process.
       A call to flock() may block if an incompatible lock is held by another process.  To make a non-blocking request,  include
       LOCK_NB (by ORing) with any of the above operations.
       A single file may not simultaneously have both shared and exclusive locks.
       Locks  created by flock() are associated with an open file table entry.  This means that duplicate file descriptors (created by, for example, fork(2) or dup(2)) refer to the same lock, and this lock may be modified or released using  any  of
       these  descriptors.   Furthermore, the lock is released either by an explicit LOCK_UN oper

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值