Linux设备树的驱动开发-应用App

Makefile

新建trng/app目录,并创建Makefile,内如如下:

# 交叉工具链
CROSS_COMPILE ?= /opt/andestech/nds32le-linux-glibc-v5d/bin/riscv32-linux-
 
# 指定C编译器
CC := $(CROSS_COMPILE)gcc
 
# 目标文件名
TARGET := trng
 
# 源文件名
SRC := trng.c
 
# 默认目标
all: $(TARGET)
 
# 编译并链接
$(TARGET): $(SRC)
	$(CC) $(SRC) -o $(TARGET)
 
# 清理
clean:
	rm -f $(TARGET)

应用

trng/app下新建trng.c文件,内容如下:

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

#define TRNG_DEVICE                       "/dev/trng"

static void hexdump(const char *name, const unsigned char *buffer, unsigned int len)
{
    printf("****************%s****************\n", name);
    for (unsigned int i = 0; i < len; i++) {
        printf("%02x ", buffer[i]);
        if ((i + 1) % 16 == 0) {
            printf("\n");
        }
    }
    if (len % 16 ) {
        printf("\n");
    }
}

int main(int argc, char *argv[])
{
    uint8_t *buf = NULL;
    size_t num;
    int ret, fd;

    if (argc < 2) {
        printf("Usage: trng <num>\n");
        return -1;
    }
    num = atoi(argv[1]);

    buf = malloc(num);
    if (buf == NULL) {
        printf("Failed to malloc\n");
        return -1;
    }

    /* 打开设备 */
    fd = open(TRNG_DEVICE, O_RDONLY);
    if (fd < 0) {
        printf("Failed to open trng device\n");
        goto exit;
    }
    
    /* 读取随机数 */
    ret = read(fd, buf, num);
    if (ret < 0) {
        printf("Failed to read random, ret=%d\n", ret);
        goto exit;
    }

    hexdump("random", buf, num);
exit:
    close(fd);
    free(buf);

    return ret;
}

执行make编译应用程序,编译成功生成trng

同理,将trng应用拷贝到trng目录,并执行:

./trng 16
# ****************random****************
# 6c 95 ea 3c a0 1f e8 c2 03 db 66 f6 19 4b 07 e3 
# c0 96 a3 93 20 a9 68 c5 9f 1f a1 55 c0 9c 24 c9 
# 5f 06 47 45 be 2c 21 b5 11 23 23 e6 36 94 3f d6 
# 9a 30 68 91 da c4 6d ff af 46 26 c9 ab f8 79 7c 

如果随机数获取成功,说明驱动和应用程序运行正常。

上一篇:string