Невозможно распечатать сообщение, отправленное из приложения пользовательского пространства C в модуль ядра Linux - PullRequest
5 голосов
/ 23 октября 2019

Я разработал простой модуль ядра Linux:

#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>


ssize_t exer_open(struct inode *pinode, struct file *pfile) {

    return 0;
}

ssize_t exer_read(struct file *pfile, char __user *buffer, size_t length, loff_t *offset) {

    return 0;
}

ssize_t exer_write(struct file *pfile, const char __user *buffer, size_t length, loff_t *offset) {

    return length;
}

ssize_t exer_close(struct inode *pinode, struct file *pfile) {

    return 0;
}

struct file_operations exer_file_operations = { 
    .owner = THIS_MODULE,
    .open = exer_open,
    .read = exer_read,
    .write = exer_write,
    .release = exer_close,
};

int exer_simple_module_init(void) {

    printk(KERN_ALERT "Inside the %s function\n", __FUNCTION__);
    register_chrdev(240, "Simple Char Drv", &exer_file_operations);
    return 0;
}

void exer_simple_module_exit(void) {

    unregister_chrdev(240, "Simple Char Drv");
}

module_init(exer_simple_module_init);
module_exit(exer_simple_module_exit);

Я без проблем вставляю этот модуль в ядро ​​с помощью команды insmod.

Я хочу использовать этот модуль дляраспечатать сообщение, отправленное ему программой пользовательского пространства, которую я тоже разработал:

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>


int main()

{

int ret, fd;
char stringToSend[] = "Hello World !";

fd = open("/dev/char_device", O_RDWR);             // Open the device with read/write access

if (fd < 0)
    {
            perror("Failed to open the device...");
            return errno;
    }

ret = write(fd, stringToSend, strlen(stringToSend)); // Send the string to the LKM

if (ret < 0)
    {
            perror("Failed to write the message to the device.");
            return errno;
    }

return 0;

}

Когда я запускаю программу и проверяю журналы ядра с помощью команды tail -f /var/log/messages, я вижу: user.alert kernel: Inside the exer_read function Но я не могусм. сообщение «Hello World!»

Я не знаю, чего мне здесь не хватает, тем более, что я все еще новичок в разработке модулей и их использовании. Помогите мне, пожалуйста!

1 Ответ

0 голосов
/ 04 ноября 2019

Для людей, которые все еще не могут найти решение для этого, у меня есть ответ.

Это модуль:

#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/device.h>  
#include <linux/kernel.h>
#include <linux/uaccess.h>


MODULE_LICENSE("GPL");      
MODULE_AUTHOR("Gaston");  
MODULE_DESCRIPTION("A simple Linux char driver"); 
MODULE_VERSION("0.1"); 

#define MAX 256

static char message[MAX] ="";           ///< Memory for the string that is passed from userspace


ssize_t exer_open(struct inode *pinode, struct file *pfile) {

    printk(KERN_INFO "Device has been opened\n");
    return 0;
}


ssize_t exer_read(struct file *pfile, char __user *buffer, size_t length, loff_t *offset) {

    return 0;
}


ssize_t exer_write(struct file *pfile, const char __user *buffer, size_t length, loff_t *offset) {
    if (length > MAX)
        return -EINVAL;

    if (copy_from_user(message, buffer, length) != 0)
        return -EFAULT;

    printk(KERN_INFO "Received %s characters from the user\n", message);
    return 0;

}   


ssize_t exer_close(struct inode *pinode, struct file *pfile) {

    printk(KERN_INFO "Device successfully closed\n");
    return 0;
}


struct file_operations exer_file_operations = { 
    .owner = THIS_MODULE,
    .open = exer_open,
    .read = exer_read,
    .write = exer_write,
    .release = exer_close,
};


int exer_simple_module_init(void) {

    printk(KERN_INFO "Initializing the LKM\n");
    register_chrdev(240, "Simple Char Drv", &exer_file_operations);
    return 0;
}


void exer_simple_module_exit(void) {

    unregister_chrdev(240, "Simple Char Drv");
}

module_init(exer_simple_module_init);
module_exit(exer_simple_module_exit);

И это приложение:

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>


#define BUFFER_LENGTH 256 

int main()

{

int ret, fd;
char stringToSend[BUFFER_LENGTH];


fd = open("/dev/char_device", O_RDWR);             // Open the device with read/write access

if (fd < 0)
    {
            perror("Failed to open the device...");
            return errno;
    }


printf("Type in a short string to send to the kernel module:\n");

scanf("%s", stringToSend);                // Read in a string (with spaces)

printf("Writing message to the device [%s].\n", stringToSend);

ret = write(fd, stringToSend, strlen(stringToSend)); // Send the string to the LKM

if (ret < 0)
    {
            perror("Failed to write the message to the device.");
            return errno;
    }

return 0;

}

Вы увидите, что это будет работать нормально.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...