Search code examples
mountlinux-kernelgpio

Mounting a file system using a C program


In my initramfs.cpio I have only these directories:

root@localhost extract]# ls 
dev  init  tmp sys 

dev has console and sys is empty.

init is a binary corresponding to program that I discussed in Accessing GPIO after kernel boots.

Now in the same GPIO program I would like to write code to mount a /sys. I understand it can be mounted using mount:

mount -t sysfs none /sys

How do I write a C program that will implement the above line. Please note that I do not have a file system; initramfs.cpio has empty folders: /sys, /tmp. I can put more empty folder if required. But I cannot put full file system.

My main intention To access GPIO using this program or otherwise, but without using a full file system. I dont need any other thing to run, but just want GPIO access (and LED blink)


Solution

  • You use the mount(2) system call. From the manpage:

    SYNOPSIS

      #include <sys/mount.h>
    
      int mount(const char *source, const char *target,
                const char *filesystemtype, unsigned long mountflags,
                const void *data);
    

    So, in your C code, that'd look something like:

    #include <sys/mount.h>
    
    /* ... */
    
    void mount_sys() {
        if (0 != mount("none", "/sys", "sysfs", 0, "")) {
            /* handle error */
        }
    }
    

    (That last empty string is where you'd pass mount options, but AFAIK sysfs doesn't take any.)