- 论坛徽章:
- 0
|
刚开始学习内核的同步知识,先按照书上的代码敲了一遍,写的是内核模块的形式,但是make之后出错了,我不知道该如何解决,请教一下啊~~拜托~我数据结构学得不好,完整程序代码如下:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/semaphore.h>
#include <linux/sched.h>
#include <asm/atomic.h>
#include <linux/delay.h>
#define PRODUCT_NUMS 10
static struct semaphore sem_producer;
static struct semaphore sem_consumer;
static char product[12];
static atomic_t num;
static int producer(void * product);
static int consumer(void * product);
static int id = 1;
static int consume_num = 1;
int init_MUTEX(&sem_producer);
//生产者线程
//该函数代表牛奶生产厂家,负责生产10批牛奶,该函数的执行受制于sem_producer信号量
//当该信号无法获取时,它将进入睡眠状态,直到信号量可用,它才能继续执行,并且释放
//sem_producer信号量
static int producer(void *p)
{
char * product = (char *)p;
int i;
atomic_inc(&num); //把1加到*num
printk("producer [%d] start……\n",current->pid);
for(i = 0;i < PRODUCT_NUMS;i++) {
down(&sem_producer);
snprintf(product,12,"2012-11-%d",id++);
//int snprintf(char *str, size_t size, const char *format, ...);
//将可变个参数(...)按照format格式化成字符串,然后将其复制到str中
printk("producer [%d] produce %s\n",current->pid,product);
up(&sem_consumer);
}
printk("producer [%d] exit……\n",current->pid);
return 0;
}
//消费者线程
//该函数代表牛奶经销商,负责批发并销售牛奶,只有生产厂家生产了牛奶,下发了批发单
//经销商才能批发牛奶,批发之后进行零售。零售完,再向牛奶生产厂家下订货单
static int consumer(void *p)
{
char *product = (char *)p;
printk("consumer [%d] start……\n",current->pid);
for(; {
msleep(100); //msleep是休眠函数,它不涉及忙等待,实际上延迟的时间可能多于100ms
down_interruptible(&sem_consumer);
if(consume_num >= PRODUCT_NUMS*atomic_read(&num))
break;
printk("comsumer [%d] consume %s\n",current->pid,product);
consume_num++;
memset(product,'\0',12);
up(&sem_producer);
}
printk("consumer [%d] exit……\n",current->pid);
return 0;
}
//模块的加载和卸载
static int procon_init(void)
{
printk(KERN_INFO"show producer and consumer\n" ;
// init_MUTEX(&sem_producer); //初始化信号量sem_producer为未锁定的互斥信号量
init_MUTEX_LOCKED(&sem_consumer); //初始化信号量sem_producer为锁定的互斥信号量
atomic_set(&num,0); //把num置成0
kernel_thread(producer,product,CLONE_KERNEL);
kernel_thread(producer,product,CLONE_KERNEL);
return 0;
}
static void procon_exit(void)
{
printk(KERN_INFO"exit producer and consumer\n" ;
}
module_init(procon_init);
module_exit(procon_exit);
MODULE_LICENSE("GPL" ;
MODULE_DESCRIPTION("producer and consumer Module" ;
MODULE_ALIAS("a simplest module" ;
makefile如下:
#makefile
obj-m:=pv.o
CURRENT_PATH := /home/helianthus
LINUX_KERNEL := $(shell uname -r)
LINUX_KERNEL_PATH := /usr/src/linux-headers-$(LINUX_KERNEL)
all:
make -C $(LINUX_KERNEL_PATH) M=/home/helianthus modules
clean:
make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) clean
运行之后出了这样的错误,我不知道咋办,没找到解决办法
|
|