Posted by: yegorich | March 4, 2016

Linux: managing kernel modules from C code

I was searching for the way to load/unload kernel modules from my C code and stumbled upon libkmod. See example below:

#include <stdio.h>
#include <libkmod.h>

int main(int argc, char **argv)
{
        int rc;
        struct kmod_ctx *my_ctx = NULL;
        struct kmod_module *my_module = NULL;

        my_ctx = kmod_new(NULL, NULL);
        if (my_ctx == NULL) {
                perror("kmod_new");
        }

        rc = kmod_module_new_from_name(my_ctx, "musb_dsps", &my_module);
        printf("rc %d\n");

        if (kmod_module_remove_module (my_module, 0)) {
                perror("rmmod ");
        }

        sleep(1);

        if (kmod_module_insert_module(my_module, 0, NULL)) {
                perror("insmod ");
        }
        return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: