linux mount

#include <stdio.h>
#include <stdlib.h>
#include <sys/mount.h>

#include <sys/types.h>
#include <unistd.h>

#undef _POSIX_SOURCE
#include <linux/capability.h>

#include <errno.h>

void whoami(void)
{
    printf("uid=%i  euid=%i  gid=%i\n", getuid(), geteuid(), getgid());
}

void caps()
{
    struct __user_cap_header_struct cap_header_data;
    cap_user_header_t cap_header = &cap_header_data;

    struct __user_cap_data_struct cap_data_data;
    cap_user_data_t cap_data = &cap_data_data;

    cap_header->pid = getpid();
    cap_header->version = _LINUX_CAPABILITY_VERSION_1;

    if (capget(cap_header, cap_data) < 0) {
        perror("Failed capget");
        exit(1);
    }
    printf("capheader: %x  %d\n", cap_header->version, cap_header->pid);  
    printf("Cap data 0x%x, 0x%x, 0x%x\n", cap_data->effective, cap_data->permitted, cap_data->inheritable);
}

void caps_set() {
    struct __user_cap_header_struct cap_header;  
  
    struct __user_cap_data_struct   cap_data;  
  
    cap_header.pid = getpid();
    cap_header.version = _LINUX_CAPABILITY_VERSION_1;  
  
    __u32 cap_mask  = 0;  
    cap_mask |= (1 << CAP_NET_BIND_SERVICE);  
    cap_mask |= (1 << CAP_SYS_ADMIN);  
    //cap_mask |= (CAP_NET_BIND_SERVICE);  
    //cap_mask |= (CAP_SYS_ADMIN);  
    cap_data.effective = cap_mask;//类似于权限的集合  
    cap_data.permitted = cap_mask;//0001000000  
    cap_data.inheritable = 0;//子进程不继承特权  
  
    if(capset(&cap_header, &cap_data) < 0)  
    {  
        printf("%s\n", strerror(errno));  
        exit(EXIT_FAILURE);  
    }
}

int main(int argc, char** argv) 
{
    char* source = NULL, *target = NULL;
    if (argc < 2) 
    {
        printf("Usage: mount source target\n");
        printf("Example: \n");
        printf("\tmount /dev/xvda1 /mnt/test\n");
        printf("\n");
        return 0;
    }

    //capset call is not required
    //whoami();
    //caps();
    //caps_set();
    //caps();

    source = argv[1];
    target = argv[2];

    printf("mounting %s on %s\n", source, target);
	//Appropriate privilege (Linux: the CAP_SYS_ADMIN capability) is required to mount file systems.
    //int err = mount(source, target, "ext4", MS_BIND, NULL);
    int err = mount(source, target, "ext4", MS_RELATIME, NULL);
    if (err == -1) 
    {
        printf("mount error: %d\n", errno);
        return errno;
    }
    printf("mounted %s on %s\n", source, target);
    return 0;
}

 

编译:

# gcc -c mounttest.c -o mounttest.o

# gcc mounttest.o  -o mounttest

# ./mounttest 

Usage: mount source target

Example: 

mount /dev/xvda1 /mnt/test

运行之前先创建挂载点:

mkdir /mnt/test

运行:

# ./mounttest /dev/xvda1 /mnt/test

mounting /dev/xvda1 on /mnt/test

mounted /dev/xvda1 on /mnt/test

猜你喜欢

转载自lobin.iteye.com/blog/2377671