當前位置:才華齋>計算機>C語言>

C語言程式介紹

C語言 閱讀(2.59W)

【提要】本篇《C語言簡單的字元驅動程式介紹》特別為需要介紹程式設計學習的'朋友收集整理的,僅供參考。內容如下:

C語言程式介紹

C語言是一種計算機程式設計語言,它既具有高階語言的特點,又具有組合語言的特點。以下是小編為大家搜尋整理的C語言簡單的字元驅動程式介紹。

程式碼分為:makefile ,核心態程式 globalmem.c 使用者態程式 user.c 功能是把一個陣列排序,你也可以使用 read write函式往記憶體裡寫東西。

  執行方法:

make,產生檔案, Insmod , 看一下 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 .* *.o *.c * _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;

27}globalmem_dev;

28

29globalmem_dev * global;

30

31typedef struct __arithmetic_st{

32 int buf[10];

33 int len;

34}arithmetic_st;

35

36

37

38

39int globalmem_open(struct 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_release(struct inode * inode, struct file * filp)

52{

53 atomic_inc(&global->ato);

54 return 0;

55}

56

57

58//read

59static ssize_t globalmem_read(struct 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 if(p > GLOBALMEM_SIZE)

68 return count ? -ENXIO : 0;