当前位置:免费学习网考试资料计算机类内容页

C语言程序介绍

2020-09-11 07:10:02 计算机类 访问手机版

  【提要】本篇《C语言简单的字符驱动程序介绍》特别为需要介绍编程学习的朋友收集整理的,仅供参考。内容如下:

  C语言是一种计算机程序设计语言,它既具有高级语言的特点,又具有汇编语言的特点。以下是小编为大家搜索整理的C语言简单的字符驱动程序介绍。

  代码分为:makefile ,内核态程序 globalmem.c 用户态程序 user.c 功能是把一个数组排序,你也可以使用 read write函数往内存里写东西。

  运行方法:

  make,产生globalmem.ko文件, Insmod globalmem.ko , 看一下 dmesg -c 是否有提示信息也可以 lsmod | grep "glo", 有的话说明加载上了,

  然后 mknod /dev globalmem c 254 0 , 看一下 ls /proc/device/ | grep "glo" 有东西没。

  然后运行用户态程序,数组被排序了。dmesg -c 可以看到提示信息, 在模块中排序了。

  上代码是带锁的代码,顺便练练手

  makefile

  1# makefile for kernel 2.6

  2ifneq $KERNELRELEASE,

  3#mymodule-objs := file1.o file2.o

  4obj-m := globalmem.o

  5

  6else

  7PWD := $shell pwd

  8KVER := $shell uname -r

  9KDIR := /lib/modules/$KVER/build

  10all:

  11 $MAKE -C $KDIR M=$PWD

  12clean:

  13 rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions

  14

  15endif

  16

  内核模块

  1#include

  2#include

  3#include

  4#include

  5#include

  6#include

  7#include

  8#include

  9#include

  10#include

  11#include "mem.h"

  12

  13#define GLOBALMEM_SIZE 0x1000

  14#define MEM_CLEAR 0x1

  15#define ARRAY_INSTER 0x2

  16#define GLOBALMEM_MAJOR 254

  17

  18static int globalmem_major = GLOBALMEM_MAJOR;

  19

  20//the struct of global

  21typedef struct __globalmem_dev

  22 struct cdev cdev;

  23 unsigned char mem[GLOBALMEM_SIZE];

  24 //add lock, signal

  25 struct semaphore sem;

  26 atomic_t ato;

  27globalmem_dev;

  28

  29globalmem_dev * global;

  30

  31typedef struct __arithmetic_st

  32 int buf[10];

  33 int len;

  34arithmetic_st;

  35

  36

  37

  38

  39int globalmem_openstruct inode *inode, struct file * filp

  40

  41 filp->private_data = global;

  42 //you can only open one file

  43 if!atomic_dec_and_test&global->ato

  44

  45 printk KERN_NOTICE "atomic is lock ";

  46 return -EBUSY;

  47

  48 return 0;

  49

  50

  51int globalmem_releasestruct inode * inode, struct file * filp

  52

  53 atomic_inc&global->ato;

  54 return 0;

  55

  56

  57

  58//read

  59static ssize_t globalmem_readstruct file * filp, char __user *buf, size_t size, loff_t *ppos

  60

  61 unsigned long p = *ppos;

  62 unsigned int count = size;

  63 int ret = 0;

  64

  65 globalmem_dev *dev = filp->private_data;

  66

  67 ifp > GLOBALMEM_SIZE

  68 return count ? -ENXIO : 0;