Linux应用程序怎么创建proc,创建和读写linux下面的/proc文件

#include #define PROCFS_NAME "myprocfile"

#define PROCFS_MAX_SIZE 1024

char proc_buffer[PROCFS_MAX_SIZE];

static long int proc_buffer_size=0;

struct proc_dir_entry *MY_PROC_FILE;

int

procfile_read(char*buffer, char**buffer_localation, off_t offset,\

int buffer_length,int* eof, void *data )

{

int ret;

printk(KERN_INFO "procfile_read(/proc/%s) called\n",PROCFS_NAME);

if(offset>0)

{

printk(KERN_INFO "file /porc/%s has been finished to read\n",PROCFS_NAME);

return 0;

}else

{

memcpy(buffer,proc_buffer,proc_buffer_size);

ret=proc_buffer_size;

}

return ret;

}

int

procfile_write(struct file *filp, const char *buffer,unsigned long count,void *data)

{

proc_buffer_size=count;

if(proc_buffer_size > PROCFS_MAX_SIZE)

{

proc_buffer_size = PROCFS_MAX_SIZE;

}

if(copy_from_user(proc_buffer, buffer, proc_buffer_size));

{

return -EFAULT;

}

return proc_buffer_size;

}

static int __init procfs_init(void)

{

MY_PROC_FILE = create_proc_entry(PROCFS_NAME,0644,NULL);

if(MY_PROC_FILE == NULL)

{

remove_proc_entry(PROCFS_NAME, &proc_root);

printk(KERN_INFO "Error:could not initialize /proc/%s\n",PROCFS_NAME);

return -ENOMEM;

}

MY_PROC_FILE->read_proc = procfile_read;

MY_PROC_FILE->write_proc = procfile_write;

MY_PROC_FILE->owner = THIS_MODULE;

MY_PROC_FILE->mode = S_IFREG | S_IRUGO;

MY_PROC_FILE->uid = 0;

MY_PROC_FILE->gid =0;

MY_PROC_FILE->size=37;

printk(KERN_INFO "/proc/%s is created\n",PROCFS_NAME);

return 0;

}

static void __exit procfs_exit(void)

{

remove_proc_entry(PROCFS_NAME, &proc_root);

printk(KERN_INFO "/proc/%s has been removed\n",PROCFS_NAME);

}

module_init(procfs_init);

module_exit(procfs_exit);

/***********************************************************************/

######### Makefile ####################

obj-m += procfs2.o

all:

make -C /lib/modules/$(shell uname -r)/build     M=$(PWD) modules

insmod procfs2.ko

clean:

rmmod procfs2

#make -C /lib/modules/$(shell uname -r)/build  M=$(PWD) clean

解释:

clean 中的make这行命令不要和rmmod同使用。实践证明在make all后,用make -C        /lib/modules/$(shell uname -r)/build  M=$(PWD) clean 命令或者用rmmod命令都可以

来注销上面加入的模块procfs2。可以利用命令demsg查看内核打印出来的最后两行信息如下:

/proc/myprocfile is created

/proc/myprocfile has been removed

说明可以成功加载和卸载模块procfs2。

注意其实跟一般的linux设备驱动一样,我们也把/proc下面的文件当成内核模块,用insmod插入到内核中运行,insmod成功后你可以用命令cat /proc/modules | grep procfs2找到procfs2作为模块已经被插入到内核中。而在同时你可以在/proc文件系统下可以看到该模块对于的文件myprocfile. 当然可以用命令

rmmod procfs2卸载掉该模块。

/proc文件系统和内核的通信的具体内容可以参看下面列出的网址上的文章。

以上程序由本人编写,编写过程中参考了以下两篇文章:http://www.ibm.com/developerworks/cn/linux/l-proc.html

向以上两位作者表示感谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值