消费者与生产者(文件读写及上锁)源代码及结果展示

producer.c#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <string.h>#include <fcntl.h>#include "mylock.h"#define MAXLEN 10 /* 缓冲区大小最大值*/#define A...
摘要由CSDN通过智能技术生成

producer.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include "mylock.h"
#define MAXLEN 10 /* 缓冲区大小最大值*/
#define ALPHABET 1 /* 表示使用英文字符 */
#define ALPHABET_START 'a' /* 头一个字符,可以用 'A'*/
#define COUNT_OF_ALPHABET 26 /* 字母字符的个数 */
#define DIGIT 2 /* 表示使用数字字符 */
#define DIGIT_START '0' /* 头一个字符 */
#define COUNT_OF_DIGIT 10 /* 数字字符的个数 */
#define SIGN_TYPE ALPHABET /* 本实例选用英文字符 */
const char *fifo_file = "./myfifo"; /* 仿真FIFO文件名 */
char buff[MAXLEN]; /* 缓冲区 */
/* 功能:生产一个字符并写入到仿真FIFO文件中 */
int product(void)
{
   
int fd;
unsigned int sign_type, sign_start, sign_count, size;
static unsigned int counter = 0;
/* 打开仿真FIFO文件 */
if ((fd = open(fifo_file, O_CREAT|O_RDWR|O_APPEND, 0644)) < 0)
{
   
printf("Open fifo file error\n");
exit(1);
}
sign_type = SIGN_TYPE;
switch(sign_type)
{
   
case ALPHABET:/* 英文字符 */
{
   
sign_start = ALPHABET_START;
sign_count = COUNT_OF_ALPHABET;
}
break;
case DIGIT:/* 数字字符 */
{
   
sign_start = DIGIT_START;
sign_count = COUNT_OF_DIGIT;
}
break;
default:
{
   
return -1;
}
}/*end of switch*/
sprintf(buff, "%c", (sign_start + counter));
counter = (counter + 1) % sign_count;
lock_set(fd, F_WRLCK); /* 上写锁*/
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值