Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1277886
  • 博文数量: 213
  • 博客积分: 7590
  • 博客等级: 少将
  • 技术积分: 2185
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-31 17:31
个人简介

热爱开源,热爱linux

文章分类

全部博文(213)

文章存档

2018年(4)

2017年(1)

2015年(1)

2014年(5)

2013年(2)

2012年(2)

2011年(21)

2010年(82)

2009年(72)

2008年(23)

分类: LINUX

2010-04-27 20:24:41


   今天编了一个简单的模块,用来遍历给定进程的父进程,子进程,以及兄弟进程:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <linux/pid_namespace.h>
#include <linux/sched.h>
#include <linux/pid.h>
#include <linux/rculist.h>
#include <linux/init_task.h>
#include <linux/syscalls.h>
#include <linux/slab.h>
#include <linux/bootmem.h>
#include <linux/pid_namespace.h>
#include <linux/list.h>

static pid_t pid;

module_param(pid,int,S_IRUGO);

static int __init hello_init(void)
{
    struct task_struct *cur_task;
    cur_task=pid_task(find_get_pid(pid),PIDTYPE_PID); //获取pid进程块

    struct task_struct *task=NULL;
    struct list_head *list;

   

    task = cur_task;
    printk("遍历进程号为%d的父进程如下:\n",pid);
    while(task->parent->pid) {
        task = task->parent;
        if (task) {
             printk(KERN_ALERT"comm=%s\tpid=%u\tstate=%ld\n",task->comm,task->pid,task->state);    
        }
    }

    printk("遍历进程号为%d的子进程如下:\n",pid);
    list_for_each(list, &(cur_task->children)) {
        task = list_entry(list, struct task_struct,children);
        printk(KERN_ALERT"comm=%s\tpid=%u\tstate=%ld\n",task->comm,task->pid,task->state);
    }

    printk("遍历进程号为%d的兄弟进程如下:\n",pid);
    list_for_each(list, &(cur_task->sibling)) {
        task = list_entry(list, struct task_struct,sibling);
        printk(KERN_ALERT"comm=%s\tpid=%u\tstate=%ld\n",task->comm,task->pid,task->state);
    }
    printk("测试进程cur_task的pid :%u\n",cur_task -> pid);
    return 0;
}

static void __exit hello_exit(void)
{
    printk(KERN_INFO "Leaving the kernel!Byebye!\n");
}

MODULE_LICENSE("GPL");//Check if the code support the protocol

module_init(hello_init);
module_exit(hello_exit);
MODULE_AUTHOR("email:ceaglechina@gmail.com");


Makefile 文件如下:

#
# Copyleft (C) 2010 caojiangfeng
#
# Makefile
#
# DATE: 27.04.2010
#
# REV:1.0.A
#
# PLATFROM: Linux/Unix
#
# REV LIST:
#     DATE: 27.04.2010
#     BY: caojiangfeng
#     MODIFICATION: standard more
#

# target

TARGET=travel_proc

# variable

obj-m := $(TARGET).o
all:
    make -C /usr/src/linux-headers-2.6.31-17-generic M=$(PWD) modules
install:
    sudo insmod $(TARGET).ko
uninstall:
    sudo rmmod $(TARGET)
clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean


测试过程如下:
make
sudo insmod travel_proc.ko pid = 8
dmesg//查看打印信息
make uninstall//卸载

阅读(845) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~