linux /proc文件系统编程实例

/*
 *proc ipsec test
 */
#include <linux/init.h>
#include <linux/module.h>
#include <linux/stat.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <linux/fs.h>
#include <asm/uaccess.h>


#define  IPSEC_CONNTRACK "ipsec_conntrack"

MODULE_AUTHOR("Qxl");
MODULE_DESCRIPTION("Proc Test Module");
MODULE_LICENSE("GPL");


static char msg[255] = {0};
static struct proc_dir_entry * p_entry = NULL;
static ssize_t ipsec_conntrack_read(struct file * file,char *data,size_t len,loff_t *offset)
{
        printk("offset %d/n",(int)*offset);
        if(*offset > 0) return 0;
        if(copy_to_user(data,msg,strlen(msg)) < 0)
                return -1;
        *offset += strlen(msg);
        return strlen(msg);
}

static ssize_t ipsec_conntrack_write(struct file *file, const char *data,size_t len,loff_t *offset)
{
        if(copy_from_user(msg,(void *)data,len))
                return -EFAULT;
        msg[len - 1] = '/0';
        printk("%s/n", msg);
        return len;
}
static struct file_operations ipsec_conntrack_ops =

{
        read:ipsec_conntrack_read,
        write:ipsec_conntrack_write,
};
static int __init proc_ipsec_init()
{
        printk("module_init/n");
        p_entry = create_proc_entry(IPSEC_CONNTRACK,S_IFREG | S_IRUGO ,proc_net);
        if(p_entry == NULL)
        {
                return -ENOMEM;
        }
        p_entry->proc_fops = &ipsec_conntrack_ops;
        return 0;
}
static void  __exit proc_ipsec_exit()
{
        printk("module cleanup/n");
        remove_proc_entry(IPSEC_CONNTRACK,proc_net);
}
module_init(proc_ipsec_init);
module_exit(proc_ipsec_exit);

 

 

#Makefile for kernel 2.4

 

CC=gcc

MODCFLAGS=-DMODULE   -D__KERNEL__   -I/usr/src/linux-2.4.20-8/include

all:proc_test.o

proc_test.o:proc_test.c
        $(CC)  $(MODCFLAGS)   -c   proc_test.c
clean:
        rm -fr *.o

 

#Makefile for kernel 2.6

obj-m := proc_test.o

KER_DIR := /lib/modules/$(shell uname -r)/build

PWD :=$(shell pwd)

default:

    $(MAKE) -C $(KER_DIR) M=$(PWD) modules

.PHONY:clean

clean:

    rm -fr *.o *.ko

编译后

#insmod proc_test.o

#cat /proc/net/ipsec_conntrack

#

#echo "1" >/proc/net/ipsec_conntrack

#cat /proc/net/ipsec_conntrack

1

实现内核与用户层的通信


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值