如何在用户空间程序中使用内核libcrc32c或相同功能?

问题描述

| 我想在自己的用户空间程序中进行一些CRC检查。而且我发现内核密码库已经在系统中,并且具有SSE4.2支持。 我尝试直接将
#include <linux/crc32c.h>
并用
-I/usr/src/linux/include/
运行gcc。但是,它不起作用。 任何使用某种
libcrc32c
方法吗?     

解决方法

您可以通过Linux上的套接字系列AF_ALG在用户空间中使用内核加密
CRC32c
(以及其他哈希/密码函数):
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/socket.h>
#include <linux/if_alg.h>
#include <sys/param.h>
#include <string.h>
#include <strings.h>

int
main (int argc,char **argv) {

    int sds[2] = { -1,-1 };

    struct sockaddr_alg sa = {
        .salg_family = AF_ALG,.salg_type   = \"hash\",.salg_name   = \"crc32c\"
    };

    if ((sds[0] = socket(AF_ALG,SOCK_SEQPACKET,0)) == -1 )
        return -1;

    if( bind(sds[0],(struct sockaddr *) &sa,sizeof(sa)) != 0 )
        return -1;

    if( (sds[1] = accept(sds[0],NULL,0)) == -1 )
        return -1;

    char *s = \"hello\";
    size_t n = strlen(s);
    if (send(sds[1],s,n,MSG_MORE) != n)
        return -1;

    int crc32c = 0x00000000;
    if(read(sds[1],&crc32c,4) != 4)
        return -1;

    printf(\"%08X\\n\",crc32c);
    return 0;
}
如果您要对文件或套接字数据进行哈希处理,则可以使用零复制方法来加快速度,以避免使用-5ѭ和/或
splice
进行内核->用户空间缓冲区复制。 快乐的编码。