device driver 3

이전것/LINUX 2016. 5. 23. 20:16

root@KMU-UBUNTU:/work/dev_simple# mknod /dev/simple c 249 0

root@KMU-UBUNTU:/work/dev_simple# ls -l /dev/simple 

crw-r--r-- 1 root root 249, 0 May 23 19:07 /dev/simple


#include <linux/kernel.h>

#include <linux/module.h>

#include <linux/init.h>

#include <linux/fs.h>

#include <asm/uaccess.h>

int simple_open(struct inode* pinode,struct file* pfile){

    printk(KERN_INFO "Open Simple\n");

    return 0;


}


int simple_release(struct inode* pinode, struct file* pfile){

    printk(KERN_INFO "Release Simple");

    return 0;

}


ssize_t simple_read(struct file* pfile, char* ubuf, size_t length,

        loff_t* offset) {

    int result;

    char message[20] = "Kim Jeong Been";

    result = copy_to_user(ubuf, message, length);

    if(result <0) {

        printk(KERN_ERR " READ ERR \n");

        return result;

    }

    return result;

}


ssize_t simple_write(struct file* pfile,const char* ubuf, size_t length,

                loff_t* offset){

    char message[20];

    int result;

    result = copy_from_user(message, ubuf, length);

    if(result <0) {

        printk(KERN_ERR " Write ERR \n");

        return result;

    }

    printk(KERN_INFO " from user : %s\n ", message);

    return 0;


}


struct file_operations simple_fops = {

    read : simple_read,
    write : simple_write,
    open : simple_open,
    release : simple_release,
};

int simple_init(void){
    int result;
    result = register_chrdev(249, "simple_driver",&simple_fops);
    if(result < 0) {
        printk(KERN_ERR "Registration Error\n");
        return result;
    }

    printk(KERN_INFO "Hello Simple\n");
    return 0;
}

void simple_exit(void){
    printk(KERN_INFO "Bye Simple\n");
    unregister_chrdev(249, "simple_driver");
}

module_init(simple_init);
module_exit(simple_exit);
MODULE_LICENSE("GPL");




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

int main(void){
    int fd;
    char buffer[20];
    char number[20] = "5112648";
    fd = open("/dev/simple", O_RDWR);
    if(fd < 0) {
        perror("open");
        exit(1);
    }

    write(fd, number, strlen(number)+1);

    read(fd,buffer,20);
    printf("from kernel : %s\n", buffer);
    close(fd);
    return 0;
}


'이전것 > LINUX' 카테고리의 다른 글

우분투 16.04 폰트 설정 변경  (0) 2016.11.16
우분투 16.04 기본셋팅  (0) 2016.11.10
device driver (2)  (0) 2016.05.16
device driver  (0) 2016.05.09
make  (0) 2016.04.04
블로그 이미지

잉비니

,