fcntl_write.c

本文提供了一个使用 C 语言实现的文件锁操作示例代码,包括读锁、写锁及解锁的功能。通过 fcntl 函数对文件进行加锁,并通过 getpid() 获取当前进程 ID 显示锁的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
void lock_set(int fd, int type)
{
struct flock lock;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len =0;
while(1){
lock.l_type = type;
if((fcntl(fd, F_SETLK, &lock)) == 0){
if( lock.l_type == F_RDLCK )
printf("read lock set by %d/n",getpid());
else if( lock.l_type == F_WRLCK )
printf("write lock set by %d/n",getpid());
else if( lock.l_type == F_UNLCK )
printf("release lock by %d/n",getpid());
return;
}
fcntl(fd, F_GETLK,&lock);
if(lock.l_type != F_UNLCK){
if( lock.l_type == F_RDLCK )
printf("read lock already set by %d/n",lock.l_pid);
else if( lock.l_type == F_WRLCK )
printf("write lock already set by %d/n",lock.l_pid);
getchar();
}
}
}
 
int main(void)
{
int fd;
fd=open("hello",O_RDWR | O_CREAT, 0666);
if(fd < 0){
perror("open");
exit(1);
}
 
lock_set(fd, F_WRLCK);
getchar();
lock_set(fd, F_UNLCK);
getchar();
close(fd);
exit(0);
}

我的系统是ubuntu22.04+ros2 humble,现在的结构目录是:xyg@xyg-T6AD:~/ros2_ws/src$ tree . ├── pca9685_hardware │   ├── CMakeLists.txt │   ├── config │   │   └── pca9685_params.yaml │   ├── include │   │   └── pca9685_hardware │   │   └── pca9685_system_hardware.hpp │   ├── package.xml │   ├── resource │   │   └── plugin_description.xml │   └── src │   └── pca9685_system_hardware.cpp └── xarm_moveit_config ├── CMakeLists.txt ├── config │   ├── initial_positions.yaml │   ├── initial_positions.yaml.bak │   ├── joint_limits.yaml │   ├── joint_limits.yaml.bak │   ├── kinematics.yaml │   ├── kinematics.yaml.bak │   ├── moveit_controllers.yaml │   ├── moveit_controllers.yaml.bak │   ├── moveit.rviz │   ├── pilz_cartesian_limits.yaml │   ├── pilz_cartesian_limits.yaml.bak │   ├── ros2_controllers.yaml │   ├── ros2_controllers.yaml.bak │   ├── temp.urdf.xacro │   ├── xarm_robot.ros2_control.xacro │   ├── xarm_robot.srdf │   ├── xarm_robot.urdf │   └── xarm_robot.urdf.xacro ├── include │   └── xarm_moveit_config ├── launch │   ├── all_in_one.launch.py │   ├── controller_manager.launch.py │   ├── demo.launch.py │   ├── main_launch.py │   ├── move_group.launch.py │   ├── moveit_rviz.launch.py │   ├── ros2_control.launch.py │   ├── rsp.launch.py │   ├── rsp.launch.py.old │   ├── setup_assistant.launch.py │   ├── spawn_controllers.launch.py │   ├── static_virtual_joint_tfs.launch.py │   └── warehouse_db.launch.py ├── meshes │   ├── base_link.STL │   ├── link_1.STL │   ├── link_2.STL │   ├── link_3.STL │   ├── link_4.STL │   ├── link_5.STL │   └── link_6.STL ├── package.xml ├── scripts │   └── install_data.py └── src
最新发布
06-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值