Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15367306
  • 博文数量: 2005
  • 博客积分: 11986
  • 博客等级: 上将
  • 技术积分: 22535
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-17 13:56
文章分类

全部博文(2005)

文章存档

2014年(2)

2013年(2)

2012年(16)

2011年(66)

2010年(368)

2009年(743)

2008年(491)

2007年(317)

分类: LINUX

2008-09-09 11:44:56

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
void *load_file(const char *fn, unsigned *_sz);
static int insmod(const char *filename);
static int rmmod(const char *modname);
void usage(void);

int main(int argc, char *argv[])
{
    const char *action = argv[1];
    const char *filename = argv[2];
    if( (argc !=3) || (strcmp(action, "-i") && strcmp(action, "-r")) )
    {
        usage();
    }
    
    if(strcmp(action, "-i") == 0)
    {
        insmod(filename);
    }
    else rmmod(filename);
}

static int insmod(const char *filename)
{
    void *module;
    unsigned int size;
    int ret;

    module = load_file(filename, &size);
    if (!module)
        return -1;

    ret = init_module(module, size, "");//系统调用sys_init_module


    free(module);

    return ret;
}

static int rmmod(const char *modname)
{
    int ret = -1;
    int maxtry = 10;

    while (maxtry-- > 0) {
        ret = delete_module(modname, O_NONBLOCK | O_EXCL);//系统调用sys_delete_module

        if (ret < 0 && errno == EAGAIN)
            usleep(500000);
        else
            break;
    }

    if (ret != 0)
        printf("Unable to unload driver module \"%s\": %s\n",
             modname, strerror(errno));

    return ret;
}

void *load_file(const char *fn, unsigned *_sz)
{
    char *data;
    int sz;
    int fd;

    data = 0;
    fd = open(fn, O_RDONLY);
    if(fd < 0) return 0;

    sz = lseek(fd, 0, SEEK_END);
    if(sz < 0) goto oops;

    if(lseek(fd, 0, SEEK_SET) != 0) goto oops;

    data = (char*) malloc(sz + 1);
    if(data == 0) goto oops;

    if(read(fd, data, sz) != sz) goto oops;
    close(fd);
    data[sz] = 0;

    if(_sz) *_sz = sz;
    return data;

oops:
    close(fd);
    if(data != 0) free(data);
    return 0;
}

void usage(void)
{
    fprintf(stderr,
            "usage: lu_module -i[r] module_name\n"
            "\n"
            "examples:\n"
            " 1.lu_module -i module_name # install module to kernel\n"
            " 2.lu_module -r module_name # remove module from kernel\n"
            "\n"
           );
    exit(1);
}


===================================================

luther@gliethttp:~$ gcc -o lu_module lu_module.c
luther@gliethttp:~$ strip lu_module
luther@gliethttp:~$ sudo ./lu_module -i hello.ko
luther@gliethttp:~$ sudo ./lu_module -r hello

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