zoukankan      html  css  js  c++  java
  • linux C 调用系统接口安装模块 范例

    代码
    #include <stdio.h>
    #include 
    <stdlib.h>
    # include 
    <sys/syscall.h>    // syscall() , __NR_init_module
    #include <sys/stat.h>
    #include 
    <errno.h>               // ENOEXEC

    #include 
    <fcntl.h>        // O_RDONLY 
    #include <sys/mman.h>    // PROT_READ , MAP_PRIVATE , MAP_FAILED

    # define init_module(mod, len, opts) syscall(__NR_init_module, mod, len, opts)
    # define delete_module(mod, flags) syscall(__NR_delete_module, mod, flags)

    #define MPI_NAME "cc_def.ko"

    void moderror(int err)
    {
        
    switch (err) {
        
    case -1/* btw: it's -EPERM */
            printf(
    "no such module");
            
    return;
        
    case ENOEXEC:
            printf( 
    "invalid module format");
            
    return;
        
    case ENOENT:
            printf( 
    "unknown symbol in module, or unknown parameter");
            
    return;
        
    case ESRCH:
            printf(
    "module has wrong symbol version");
            
    return ;
        
    case ENOSYS:
            printf(
    "kernel does not support requested operation");
            
    return ;
        
    default :
            printf(
    "unknown errcode");
            
    return ;
        }
    }

    int main(void )
    {
        
    int len;
        
    char *image;
        
    const char *options;
        
    struct stat st;
        
    int fd;
        
    int ret;

        
    //if (!options)
        options = "";
        
    if ((fd = open(MPI_NAME, O_RDONLY, 0)) < 0) {
                        printf(
    "cannot open module `%s'", MPI_NAME);
            }
                fstat(fd, 
    &st);
                len 
    = st.st_size;
        printf(
    " size : %d",len);
                image 
    = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0);
                
    if (image == MAP_FAILED) {
            printf(
    "cannot mmap `%s'", MPI_NAME);
            }
        errno
    =0;
        ret
    = init_module(image, len, options);
               
    if (ret != 0) { 
            printf(
    "cannot insert ");
            moderror(errno);
            printf(
    "\n ");
        }
        munmap(image,len);
        
    return 0;
    }
  • 相关阅读:
    HDU 1069 Monkey and Banana
    HDU 1029 Ignatius and the Princess IV
    HDU 1024 Max Sum Plus Plus
    Gym100923H Por Costel and the Match
    Codeforces 682C Alyona and the Tree
    Codeforces 449B Jzzhu and Cities
    Codeforces (ccpc-wannafly camp day2) L. Por Costel and the Semipalindromes
    Codeforces 598D (ccpc-wannafly camp day1) Igor In the Museum
    Codeforces 1167c(ccpc wannafly camp day1) News Distribution 并查集模板
    快乐数问题
  • 原文地址:https://www.cnblogs.com/leaven/p/1717369.html
Copyright © 2011-2022 走看看