如何在用户空间程序中使用内核libcrc32c(或相同的函数)?

Gal*_*axy 8 c kernel

我想在我自己的用户空间程序中进行一些CRC检查.我发现内核加密lib已经在系统中,并且支持SSE4.2.

我试着直接#include <linux/crc32c.h>用gcc运行-I/usr/src/linux/include/.但是,它不起作用.

libcrc32c什么方法可以使用某种?

Mir*_*sin 9

您可以CRC32c在Linux上通过套接字系列AF_ALG使用来自用户空间的内核加密(以及其他散列/密码函数):

#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;
}
Run Code Online (Sandbox Code Playgroud)

如果你正在散列文件或套接字数据,你可以使用零拷贝方法加速它,以避免内核 - >用户空间缓冲区复制sendfile和/或splice.

快乐的编码.