0

私はLinuxカーネルモジュールの開発に不慣れで、カーネルモジュールからユーザー空間プロセスへのメモリセグメントを共有して、データのコピーの待ち時間を逃れる方法を探しています。

sys v 共有メモリ API を使用しています。2 つのプロセス間でメモリを共有すると問題なく動作しますが、プロセスとカーネル モジュール間でメモリを共有できません。

以下は、カーネルモジュールとユーザー空間アプリの私のコードです

サーバー側: モジュール

#include <linux/module.h> // init_module, cleanup_module //
#include <linux/kernel.h> // KERN_INFO //
#include <linux/types.h> // uint64_t //
#include <linux/kthread.h> // kthread_run, kthread_stop //
#include <linux/delay.h> // msleep_interruptible //
#include <linux/syscalls.h> // sys_shmget //

#define BUFSIZE 100
#define SHMSZ BUFSIZE*sizeof(char)
key_t KEY = 5678;

static struct task_struct *shm_task = NULL;


static char *shm = NULL;
static int shmid;

static int run_thread( void *data )
{
    char strAux[BUFSIZE];
    shmid = sys_shmget(KEY, SHMSZ, IPC_CREAT | 0666);
    if( shmid < 0 )
    {
        printk( KERN_INFO "SERVER : Unable to obtain shmid\n" );
        return -1;
    }
    shm = sys_shmat(shmid, NULL, 0);
    if( !shm )
    {
        printk( KERN_INFO "SERVER : Unable to attach to memory\n" );
        return -1;
    }
    strncpy( strAux, "hello world from kernel module", BUFSIZE );
    memcpy(shm, strAux, BUFSIZE);
    return 0;
}

int init_module()
{
    printk( KERN_INFO "SERVER : Initializing shm_server\n" );
    shm_task = kthread_run( run_thread, NULL, "shm_server" );
    return 0;
}

void cleanup_module()
{
    int result;
    printk( KERN_INFO "SERVER : Cleaning up shm_server\n" );
    result = kthread_stop( shm_task );
    if( result < 0 )
    {
        printk( KERN_INFO "SERVER : Unable to stop shm_task\n" );
    }
    result = sys_shmctl( shmid, IPC_RMID, NULL );
    if( result < 0 )
    {
        printk( KERN_INFO
        "SERVER : Unable to remove shared memory from system\n" );
    }

}


MODULE_LICENSE( "GPL" );
MODULE_AUTHOR( " MBA" );
MODULE_DESCRIPTION( "Shared memory  server" );

クライアント側: プロセス

#include <sys/ipc.h> // IPC_CREAT, ftok //
#include <sys/shm.h> // shmget, ... //
#include <sys/sem.h> // semget, semop //
#include <stdio.h> // printf //
#include <string.h> // strcpy //
#include <stdint.h> // uint64_t //

#define BUFSIZE 4096
key_t KEY = 5678;

int main(int argc, char *argv[]) {
    int shmid, result;
    char *shm = NULL;

    shmid = shmget(KEY, BUFSIZE, 0666);
    if (shmid == -1) {
        perror("shmget");
        exit(-1);
    }
    shm = shmat(shmid, NULL, 0);
    if (!shm) {
        perror("shmat");
        exit(-1);
    }

    printf("%s\n", shm);
    result = shmdt(shm);
    if (result < 0) {
        perror("shmdt");
        exit(-1);
    }
}

どんな提案や文書も役に立ちます。

4

1 に答える 1