在linux下编译一个简单的字符模块,模块在/proc目录下生成一个记录系统进程的内存文件ps。
get.c通过读取ps的内容来打印出进程信息。
字符模块ps.c传递代码如下:
#include
#include
#include
#include
#include
#include
MODULE_LICENSE("GPL");
MODULE_AUTHOR("cxt");
static int find_read(char *buffer, char **buffer_location, off_t offset, int count, int *eof, void *data)
{
struct task_struct *p;
char tmp[128];
if(offset >0)
return 0;
memset(buffer,0,sizeof(buffer));
//read_lock(&tasklist_lock);
for_each_process(p) //遍例内核进程链表.
{
sprintf(tmp,"%d/t/t%d/t/t/t%s/n",p->pid,p->parent->pid,p->comm);
strcat(buffer,tmp);
memset(tmp,0,sizeof(tmp));
}
//read_unlock(&tasklist_lock);
return strlen(buffer);
}
static int __init find_init(void)
{
struct proc_dir_entry *entry;
entry = create_proc_entry("ps", 0444, &proc_root);
if (entry == 0)
{
printk(KERN_ERR "creat_proc_entry failed/n");
return -1;
}
entry->mode = S_IFREG | 0444;
entry->size = 1024;
//entry->owner = THIS_MODULE;
//entry->uid = 0;
//entry->gid = 0;
entry->read_proc = find_read;
return 0;
}
void __exit find_exit(void)
{
remove_proc_entry("ps", &proc_root);
}
module_init(find_init);
module_exit(find_exit);
Makefile的内容如下:
TARGET = ps
obj-m := $(TARGET).o
KERNELDIR=/lib/modules/`uname -r`/build
PWD=`pwd`
default :
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
install :
insmod $(TARGET).ko
uninstall :
rmmod $(TARGET).ko
clean :
rm -rf *.o *.mod.c *.ko
程序get.c的代码如下:
#include
#include
#include
#include
#include
int main()
{
int fd;
char buf[1024];
fd = open("/proc/ps", O_RDONLY);
if (fd < 0)
{
printf("error/n");
exit(1);
}
//bzero(buf, sizeof(buf));
if (read(fd, buf, 1024) < 0)
{
printf("read error/n");
exit(1);
}
printf("process info :/npid/tppid/t/tname /n%s/n", buf);
//printf("getpid = %d/n", getpid());
return 0;
}
运行过程如下:
[root@localhost proc_c]# make
make -C /lib/modules/`uname -r`/build M=`pwd` modules
make[1]: Entering directory `/usr/src/kernels/2.6.18-1.2798.fc6-i586'
Building modules, stage 2.
MODPOST
make[1]: Leaving directory `/usr/src/kernels/2.6.18-1.2798.fc6-i586'
[root@localhost proc_c]# insmod ps.ko[root@localhost proc_c]# gcc -o get get.c [root@localhost proc_c]# ./getprocess info :pid ppid name 1 0 init2 1 migration/03 1 ksoftirqd/04 1 watchdog/05 1 events/06 1 khelper7 1 kthread10 7 kblockd/011 7 kacpid72 7 cqueue/075 7 khubd77 7 kseriod135 7 pdflush136 7 pdflush137 7 kswapd0138 7 aio/0286 7 kpsmoused316 7 scsi_eh_0321 7 kmirrord328 7 kjournald349 7 kauditd375 1 udevd710 7 kgameportd1266 7 kmpathd/01289 7 kjournald1295 1 vmhgfs1297 7 kjournald1645 1 syslogd1648 1 klogd1675 1 portmap1694 1 rpc.statd1723 1 rpc.idmapd1790 1 vmmemctl1856 1 vmware-guestd1878 1 dbus-daemon1887 1 hcid1899 1 sdpd1910 1 krfcommd1945 1 pcscd1962 1 hidd1976 1 automount1993 1 acpid2002 1 hpiod2007 1 python2017 1 cupsd2026 1 sshd2036 1 xinetd2048 1 ntpd2065 2048 ntpd2118 1 gpm2127 1 crond2162 1 xfs2179 1 atd2193 1 yum-updatesd2212 1 hald2213 2212 hald-runner2219 2213 hald-addon-acpi2224 2213 hald-addon-keyb2236 2213 hald-addon-stor2310 1 smartd2315 1 mingetty2316 1 mingetty