实验1
来源:互联网 发布:java注释声明 编辑:程序博客网 时间:2024/05/21 20:21
#include <stdio.h>
int main()
{
printf("hello world");
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdlib.h>
/*struct flock
{
short 1_type;
off_t 1_start;
short 1_whence;
off_t 1_len;
pid_t 1_pid;
}old_lock,lock;*/
int lock_set(int fd,int type)
{
struct flock old_lock,lock;
lock.l_whence = SEEK_SET; //相对位移量的起点:当前位置为文件开头
lock.l_start = 0; //加锁区域的相对位移量
lock.l_len = 0; //加锁区域长度
lock.l_type = type; //锁的类型
lock.l_pid = -1; //记录持有锁的进程
fcntl(fd,F_GETLK,&lock); //fd;根据参数3决定文件是否上锁;struct flock:记录锁的具体状态 总:判断文件是否可以上锁
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);
}
}
lock.l_type = type; //l_type的值可能已被F_GETLK修改过
if((fcntl(fd,F_SETLKW,&lock)) < 0) //阻塞式上锁
{
printf("Lock failed:type = %d\n",lock.l_type);
return 1;
}
switch(lock.l_type)
{
case F_RDLCK:
{
printf("Read lock set by %d\n",getpid());
}
break;
case F_WRLCK:
{
printf("Write lock set by%d\n",getpid());
}
break;
case F_UNLCK:
{
printf("Release lock by %d\n",getpid());
return 1;
}
break;
default:
break;
}
return 0;
}
写入锁函数1:
int main(void)
{
int fd;
fd = open("hello.c",O_RDWR|O_CREAT,0644);
if(fd<0)
{
printf("open file error\n");
exit(1);
}
lock_set(fd,F_WRLCK); //给文件写入锁
getchar();
lock_set(fd,F_UNLCK); //给文件解锁
getchar();
close(fd);
exit(0);
读取锁函数2:
int main(void)
{
int fd;
fd =open("hello.c",O_RDWR|O_CREAT,0644);
if(fd<0)
{
printf("open file error\n");
exit(1);
}
lock_set(fd,F_RDLCK);//给文件读取锁
getchar();
lock_set(fd,F_UNLCK);//给文件解锁
getchar();
close(fd);
exit(0);
}
}- 实验1
- 实验1
- 实验1
- 实验 1
- 实验1
- 实验1
- 实验1
- 实验1
- 实验1
- 实验1 熟悉实验环境
- CSAPP课程实验 bomb实验 拆炸弹实验(1)
- 实验一 计算机网络基础实验报告1
- 1-7 实验6 NV操作实验
- 实验1 RDBMS安装与配置实验
- 实验二:线性表实验(1)
- 《数据结构》实验二:线性表实验(1)
- 《数据结构》实验二:线性表实验(1)
- 实验:C++实验2—1
- SVN的简单使用(Ubuntu 12.04当服务端 Win 7当客户端)
- strnlen_s和strlen函数的区别
- ios UIButton点击事件(@selector)注意事项
- NSUserDefaults
- Category(分类)
- 实验1
- Spring配置文件
- Jmeter 多台机器产生负载及问题解决方法
- 判断是否为合法排序二叉树
- Linux入门
- Android过渡动画之共享元素实现以及遇到的一些问题
- 《统计学习方法》+感知机+C++代码(简单)实现
- 实验2
- apache记录真实的访问IP地址