如何从Linux内核空间模块执行/调用用户空间定义的函数?

问题描述 投票:2回答:1

我正在开发要用于从内核模式运行C程序的Linux模块。

这里的问题是,在模块的功能read()中,我需要使用在用户空间程序中定义的名为eval_keycode()的功能。

[当我尝试编译我的模块时,会发生此错误:

错误:函数'eval_keycode'的隐式声明

这正在确认我的上述问题。

这是我模块的read()功能:

ssize_t exer_read(struct file *pfile, char __user *buffer, size_t length, loff_t *offset) {
    struct file *f = pfile->private_data;
    enum { MAX_BUF_SIZE = 4096 };
    size_t buf_size = 0;
    char *buf = NULL;
    ssize_t total = 0;
    ssize_t rc = 0;

    struct input_event  *ev;
    int yalv;

    /* Allocate temporary buffer. */
    if (length) {
        buf_size = min_t(size_t, MAX_BUF_SIZE, length);
        ev = kmalloc(buf_size, GFP_KERNEL);
        if (ev == NULL) {
            return -ENOMEM;
        }
    }

    /* Read file to buffer in chunks. */
    do {
        size_t amount = min_t(size_t, length, buf_size);

        rc = kernel_read(f, ev, amount, offset);
        if (rc > 0) {
            /* Have read some data from file. */
            if (copy_to_user(buffer, ev, rc) != 0) {
                /* Bad user memory! */
                rc = -EFAULT;
            } else {
                /* Update totals. */
                total += rc;
                buffer += rc;
                *offset += rc;
                length -= rc;

        for (yalv = 0; yalv < (int) (rc / sizeof(struct input_event)); yalv++) {
            if (ev[yalv].type == EV_KEY) {
                if (ev[yalv].value == 0)
                    eval_keycode(ev[yalv].code);
            }
        }


                if (rc < amount) {
                    /* Didn't read the full amount, so terminate early. */
                    rc = 0;
                }
            }
        }
    } 
    while (rc > 0 && length > 0);

    /* Free temporary buffer. */
    kfree(buf);

    if (total > 0) {
       return total;
    }
    return rc;
}

这是我的用户空间eval_keycode()定义的功能:

void eval_keycode(int code)
{
    static int red_state = 0;
    static int green_state = 0;

    switch (code) {
    case 260:
        printf("BTN left pressed\n");

        /* figure out red state */
        red_state = red_state ? 0 : 1;

        change_led_state(LED_PATH "/" red "/brightness", red_state);
        break;

    case BTN_RIGHT:
        printf("BTN right pressed\n");

        /* figure out green state */
        green_state = green_state ? 0 : 1;

        change_led_state(LED_PATH "/" green "/brightness", green_state);
        break;
    }
}

如何从用户空间调用eval_keycode函数来解决此问题?

谢谢。

c linux-device-driver embedded-linux kernel-module
1个回答
0
投票

没有传统的(以库的工作方式)“调用”用户空间“功能”的方法。

您的用户空间代码应在其自己的进程(或另一个用户空间进程)中运行,您将在其中执行通信(通过共享内存,进程间调用[IPC],设备文件,中断..),并在其中进行通信。交换数据,并对数据采取行动(例如,调用eval_keycode函数)。

© www.soinside.com 2019 - 2024. All rights reserved.