Device File

moonsyu·2026년 11월 24일

Embedded

목록 보기
35/37
post-thumbnail

Linux 장치 제어 방법

  • User Space의 App은 Kernel Space에 직접 접근할 수 없다.
  • App은 Device Driver와 연결된 Device File에 System Call을 보내 장치를 제어한다.
  1. App에서 Device File로 SysCall 전송
  2. Device File과 연결되어 있는 Device Driver가 H/W 제어

User Space의 앱이 System Call과 장치 파일을 통해 Kernel Space의 드라이버에 작업을 요청하고 하드웨어를 제어하는 흐름

  • Device File을 열고(open), 읽고(read), 쓰고(write), 닫는(close) 방식으로 장치를 다룬다.
  • 일반 파일을 다루는 System Call과 같으므로, App 개발자는 장치를 파일처럼 다룰 수 있다.

앱의 open 요청이 VFS와 장치 파일의 Major·Minor 번호를 거쳐 드라이버의 fops로 연결되는 과정

Device File이란

  • 장치를 제어하기 위해 /dev/에 등록되는 파일
  • Device Node라고도 부른다
  • /dev/ 안에 실제 장치 or 가상 장치가 존재
  • /dev/ 안의 파일 종류 4가지 (c, b, l, d)
    • c : character device file
    • b : block device file
    • l : 심볼릭 링크, d : 디렉토리 (장치 파일은 아님)

실제 장치
Character 장치 파일을 통한 I2C 통신과 Block 장치 파일을 통한 SD카드 접근 예시

가상 장치
가상 장치인 null, zero, random, loop0의 기능과 Character·Block 구분

c와 b의 차이

  • 실제 장치냐 가상 장치냐가 아니라, 데이터를 주고받는 방식으로 구분한다.
구분c (Character)b (Block)
데이터 단위Byte 단위 스트림Block 단위 (512B, 4KB 등)
접근 방식순차 접근임의 위치 접근 가능
Buffer/Cache대부분 바로 전달커널이 Cache 후 처리
실제 장치UART, I2C, 키보드, GPIOSD카드, SSD, USB 메모리
가상 장치/dev/null, /dev/zero, /dev/randomloop0 ~ loop7

[참고] ls -l로 파일 종류 확인

ls -l /dev | cut -c1 | sort | uniq -c
  • 맨 앞 글자가 파일 종류를 나타낸다.
  • c, b 외에 p(Named Pipe), s(Socket)도 특수 파일이지만 장치 파일은 아니다.

Device File 옵션

  • Major, Minor로 장치 파일을 구분한다
  • 파일 이름이 아니라 번호로 Device Driver와 연결된다.
  • Major Number (주 번호)
    • 기기 종류를 나타냄
    • 같은 기능을 하는 디바이스가 여러개 있다면, 동일한 주번호를 가짐
    • 커널은 Major 번호로 어떤 Device Driver를 호출할지 찾는다.
  • Minor Number (부 번호)
    • 동일한 종류의 device에서 구분하는 용도
    • 개발자 임의로 의미 부여 가능
    • blkdev에서는 파티션 번호로 사용

ls -l 결과에서 크기 자리에 주번호, 부번호가 표시된다.

crw-rw---- 1 root i2c 89, 20 ... i2c-20
brw-rw---- 1 root disk 7,  0 ... loop0
  • i2c-20 : Major 89 (I2C 드라이버), Minor 20 (20번 버스)
  • loop0 : Major 7 (loop 드라이버), Minor 0 (0번 loop 장치)

Device File 생성 - 1 (mknod)

mknod 유틸리티

  • Device File(Node)을 만드는 유틸리티
  • 일반적으로 /dev/에 생성해서 관리한다.
  • root 권한이 필요하다.

형식

sudo mknod [파일명] [파일종류] [Major] [Minor]

생성 → 확인

sudo mknod /dev/deviceFile c 100 0
ls -al /dev/deviceFile
  • deviceFile이라는 이름의 Character Device File을 Major 100, Minor 0으로 생성한다.
  • ls -al 결과 맨 앞이 c, 크기 자리가 100, 0이면 정상이다.

실습 파일

~/test2 폴더에 devicedriver.c, Makefile을 만든다.

devicedriver.c

#include <linux/module.h>  // module_init 등 모듈 매크로
#include <linux/printk.h>  // pr_info 등 커널 로그
#include <linux/init.h>    // __init / __exit 매크로
#include <linux/fs.h>      // file_operations, register_chrdev

#define NOD_MAJOR 100          // mknod로 만든 장치 파일의 Major 번호
#define NOD_NAME "deviceFile"  // 등록할 Character Device 이름

MODULE_LICENSE("GPL");

// deviceFile에 open() 호출 시 실행
static int deviceDriver_open(struct inode *inode, struct file *filp){
    pr_info("Open Device\n");
    return 0;
}

// deviceFile에 close() 호출 시 실행
static int deviceDriver_release(struct inode *inode, struct file *filp){
    pr_info("Close Device\n");
    return 0;
}

static struct file_operations fops = {
    .owner = THIS_MODULE,
    .open = deviceDriver_open,
    .release = deviceDriver_release,
};

// insmod 시 실행
static int __init deviceDriver_init(void)
{
    int ret = register_chrdev(NOD_MAJOR, NOD_NAME, &fops);
    if( ret < 0 ){
        pr_alert("Register File\n");
        return ret;
    }

    pr_info("Insmod Module\n");
    return 0;
}

// rmmod 시 실행
static void __exit deviceDriver_exit(void)
{
    unregister_chrdev(NOD_MAJOR, NOD_NAME);
    pr_info("Unload Module\n");
}

module_init(deviceDriver_init);
module_exit(deviceDriver_exit);

Makefile

KERNEL_HEADERS=/lib/modules/$(shell uname -r)/build
obj-m += devicedriver.o
PWD := $(CURDIR)

driver:
	make -C $(KERNEL_HEADERS) M=$(PWD) modules

clean:
	make -C $(KERNEL_HEADERS) M=$(PWD) clean
  • /lib/modules/$(uname -r)/build는 현재 실행 중인 커널의 소스(헤더) 위치를 가리킨다.
  • 이 경로가 없으면 빌드가 실패하므로, 모듈은 실행 중인 커널과 같은 버전으로 빌드해야 한다.

빌드 → 적재 → 확인 → 해제

make
sudo insmod ./devicedriver.ko
sudo cat /dev/deviceFile
sudo rmmod devicedriver
dmesg | tail

커널 로그

Insmod Module
Open Device
Close Device
Unload Module
  • cat이 내부적으로 open(), close()를 호출하므로 Open Device, Close Device가 찍힌다.

mknod로 장치 파일을 준비한 뒤 insmod, cat, rmmod를 실행할 때의 커널 로그 예시

[참고] 커널 로그 실시간 확인

sudo dmesg -wH
  • 터미널 하나에 띄워두고, 다른 터미널에서 insmod / cat / rmmod를 실행하면 로그를 바로 확인할 수 있다.
  • journalctl -kf로도 같은 내용을 볼 수 있다.

코드 설명

<linux/fs.h>

  • File System 접근을 위한 헤더
  • file_operations(fops) 구조체, register_chrdev()가 정의되어 있다.

open() / release()

static int deviceDriver_open(struct inode *inode, struct file *filp)
  • inode : Device File의 inode 정보 (Major, Minor 번호 등)
  • filp : 열린 파일을 나타내는 파일 포인터
  • /dev/deviceFile에 open / close System Call을 보내면 호출된다.
  • close()에 대응하는 함수 이름은 close가 아니라 release이다.

struct file_operations

  • System Call에 대응할 함수들의 포인터를 모아둔 구조체
  • 구조체 지정 초기화로 필요한 항목만 등록한다.
  • .owner : 이 fops를 가진 모듈, THIS_MODULE 매크로로 지정 (사용 중 모듈이 내려가는 것을 막는다)
  • .open : deviceDriver_open() 등록
  • .release : deviceDriver_release() 등록

fops 동작 방법

  • Device File에 특정 System Call을 보내면, fops에 등록된 함수가 호출된다.
    • open() → .open → deviceDriver_open()
    • close() → .release → deviceDriver_release()
    • read() → .read, write() → .write, ioctl() → .unlocked_ioctl

open과 close가 file_operations의 open과 release를 통해 드라이버 함수에 연결되는 관계

register_chrdev() / unregister_chrdev()

int register_chrdev(unsigned int major, const char *name, const struct file_operations *fops);
void unregister_chrdev(unsigned int major, const char *name);
  • 커널이 관리하는 Character Device 목록에 드라이버를 등록 / 해제한다.
  • major : Major 번호
  • name : 장치 이름 (/proc/devices에 표시됨)
  • fops : System Call에 대응할 함수 목록
  • 드라이버만 등록할 뿐 /dev/에 파일을 만들지는 않는다. 그래서 mknod가 따로 필요하다.

등록 확인

cat /proc/devices | grep deviceFile
100 deviceFile

mknod 방식의 단점

  • /dev/는 부팅 시 메모리에 새로 만들어지는 영역(devtmpfs)이다.
  • 그래서 mknod로 만든 파일은 재부팅하면 사라진다.
sudo reboot
ls -al /dev/deviceFile
ls: '/dev/deviceFile'에 접근할 수 없습니다: 그런 파일이나 디렉터리가 없습니다
  • Major 번호를 직접 정하므로 이미 사용 중인 번호와 겹칠 수 있다.
  • 해결 : Device Driver 코드에서 Device File을 직접 생성한다.

Device File 생성 - 2 (device_create)

실습 파일

~/test3 폴더에 devicedriver.c, Makefile(test2와 동일)을 만든다.

devicedriver.c

#include <linux/module.h>
#include <linux/printk.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/device.h>  // class_create, device_create

#define NOD_NAME "deviceFile"  // 만들 장치 파일 이름 (/dev/deviceFile)

MODULE_LICENSE("GPL");

static int NOD_MAJOR;       // 커널이 할당한 Major 번호
static struct class *cls;   // Device File을 관리할 class
static dev_t dev;           // Major + Minor 장치 번호

static int deviceDriver_open(struct inode *inode, struct file *filp){
    pr_info("Open Device\n");
    return 0;
}

static int deviceDriver_release(struct inode *inode, struct file *filp){
    pr_info("Close Device\n");
    return 0;
}

static struct file_operations fops = {
    .owner = THIS_MODULE,
    .open = deviceDriver_open,
    .release = deviceDriver_release,
};

static int __init deviceDriver_init(void)
{
    // major를 0으로 주면 커널이 빈 번호를 할당해서 return
    NOD_MAJOR = register_chrdev(0, NOD_NAME, &fops);
    if( NOD_MAJOR < 0 ){
        pr_alert("Register File\n");
        return NOD_MAJOR;
    }

    pr_info("Insmod Module\n");

    dev = MKDEV(NOD_MAJOR, 0);                       // 장치 번호 생성
    cls = class_create(NOD_NAME);                    // class 생성
    device_create(cls, NULL, dev, NULL, NOD_NAME);   // /dev/deviceFile 생성

    pr_info("Major number %d\n", NOD_MAJOR);
    pr_info("Device file : /dev/%s\n", NOD_NAME);

    return 0;
}

static void __exit deviceDriver_exit(void)
{
    device_destroy(cls, dev);                // /dev/deviceFile 삭제
    class_destroy(cls);                      // class 삭제
    unregister_chrdev(NOD_MAJOR, NOD_NAME);  // 드라이버 해제
    pr_info("Unload Module\n");
}

module_init(deviceDriver_init);
module_exit(deviceDriver_exit);

빌드 → 적재 → 확인 → 해제

make
sudo insmod ./devicedriver.ko
ls -al /dev/deviceFile
sudo cat /dev/deviceFile
sudo rmmod devicedriver
ls -al /dev/deviceFile
dmesg | tail
  • insmod만 해도 /dev/deviceFile이 생기고, rmmod하면 사라진다.
  • mknod 없이 사용할 수 있고, 재부팅 후에도 insmod하면 다시 생성된다.

커널 로그

Insmod Module
Major number 2xx
Device file : /dev/deviceFile
Open Device
Close Device
Unload Module
  • Major 번호는 커널이 할당하므로 환경마다 다르다.

device_create와 device_destroy를 사용하는 예제에서 insmod 전후와 rmmod 후 장치 파일의 상태

코드 설명

<linux/device.h>

  • Device File 관리용 헤더
  • class_create(), device_create() 등 Device File 생성 및 관리 API가 정의되어 있다.
  • 전역 변수
    • NOD_MAJOR : 커널이 할당한 Major 번호
    • struct class *cls : Device File을 묶어서 관리하는 class
    • dev_t dev : 장치 구분을 위한 번호 (Major + Minor)

Major 번호 동적 할당

NOD_MAJOR = register_chrdev(0, NOD_NAME, &fops);
  • major 자리에 0을 넣으면 커널이 비어 있는 번호를 할당해 return한다.
  • 다른 드라이버와 번호가 겹치는 것을 신경 쓰지 않아도 된다.
  • 실패하면 음수(에러 코드)를 return한다.

MKDEV()

dev_t MKDEV(major, minor)
  • Major, Minor 번호를 합쳐 dev_t 타입으로 만든다.
  • 커널 내부에서 dev_t는 상위 12bit가 Major, 하위 20bit가 Minor이다.
    • ex) MKDEV(1, 5) → 0x00100005
  • 반대로 MAJOR(dev), MINOR(dev)로 다시 분리할 수 있다.
  • device_create(), device_destroy()에 사용한다.

커널 내부 dev_t의 Major 12비트와 Minor 20비트 구조 및 MKDEV(1, 5)의 값

class_create()

struct class *class_create(const char *name);
  • Device File들을 그룹으로 묶어 관리하는 class를 생성한다.
  • 생성하면 /sys/class/[name]/ 이 만들어진다.
  • 커널 버전에 따라 매개변수가 다르다.
    • 6.4 미만 : class_create(THIS_MODULE, name)
    • 6.4 이상 : class_create(name)
  • 빌드 에러가 나면 uname -r로 커널 버전을 확인한다.

device_create()

struct device *device_create(struct class *class, struct device *parent,
                             dev_t devt, void *drvdata, const char *fmt, ...);
  • Device File을 생성하는 API
  • class : 위에서 만든 class
  • parent : 부모 장치, 없으면 NULL
  • devt : MKDEV()로 만든 장치 번호
  • drvdata : 드라이버 데이터, 없으면 NULL
  • fmt : Device File 이름 (printf 형식 사용 가능)

[참고] /dev/ 파일이 자동으로 생기는 원리

  • device_create()가 /sys/class/[class]/[장치]/에 장치 정보(uevent)를 등록한다.
  • 커널(devtmpfs)과 udev가 이 정보를 보고 /dev/에 Device File을 만든다.
  • 그래서 mknod를 직접 실행하지 않아도 된다.

device_create로 장치를 등록하면 devtmpfs가 노드를 만들고 udev가 권한과 링크를 설정하는 과정

device_destroy() / class_destroy()

void device_destroy(struct class *class, dev_t devt);
void class_destroy(struct class *class);
  • device_destroy() : Device File 삭제
  • class_destroy() : class 삭제
  • 생성의 역순으로 해제한다.
    • 생성 : register_chrdev → class_create → device_create
    • 해제 : device_destroy → class_destroy → unregister_chrdev

정리

구분mknod 방식device_create 방식
Device File 생성사용자가 mknod 실행insmod 시 드라이버가 생성
Major 번호직접 지정 (중복 위험)커널이 동적 할당
재부팅 후파일 사라짐, 다시 mknodinsmod하면 다시 생성
모듈 해제 시파일 남아 있음파일 자동 삭제

0개의 댓글