1 源码流程
实现U盘的自动挂接,在/etc/mdev.conf文件里加入一行语句就能实现自动装载u盘。
如何调用到/etc/mdev.conf,以之前的驱动为例,创建设备
device_create --->
device_create_vargs --->
device_register --->
device_add --->
kobject_uevent --->
kobject_uevent_env
int kobject_uevent_env(struct kobject *kobj, enum kobject_action action,
char *envp_ext[])
{
//获取字符串"add"
const char *action_string = kobject_actions[action];
...
//设置参数
retval = add_uevent_var(env, "ACTION=%s", action_string);
if (retval)
goto exit;
retval = add_uevent_var(env, "DEVPATH=%s", devpath);
if (retval)
goto exit;
retval = add_uevent_var(env, "SUBSYSTEM=%s", subsystem);
if (retval)
goto exit;
....
if (uevent_helper[0]) {
char *argv [3];
argv [0] = uevent_helper;
argv [1] = (char *)subsystem;
argv [2] = NULL;
retval = add_uevent_var(env, "HOME=/");
if (retval)
goto exit;
retval = add_uevent_var(env,
"PATH=/sbin:/bin:/usr/sbin:/usr/bin");
if (retval)
goto exit;
//调用应用程序,根据传入的环境变量参数来创建设备节点
retval = call_usermodehelper(argv[0], argv,
env->envp, UMH_WAIT_EXEC);
}
...
}
根据/sbin/mdev就进入了busybox的mdev.c的mdev_main()函数里
int mdev_main(int argc UNUSED_PARAM, char **argv)
{
...
action = getenv("ACTION");//获取参数
env_path = getenv("DEVPATH");
...
snprintf(temp, PATH_MAX, "/sys%s", env_path);
if (!strcmp(action, "remove"))
make_device(temp, 1);
else if (!strcmp(action, "add")) {
make_device(temp, 0);
...
}
static void make_device(char *path, int delete)
{
...
device_name = bb_basename(path);//获取设备节点名称
...
#if ENABLE_FEATURE_MDEV_CONF
parser = config_open2("/etc/mdev.conf", fopen_for_read);//打开配置文件
...
#endif /* ENABLE_FEATURE_MDEV_CONF */
if (!delete && major >= 0) {
if (ENABLE_FEATURE_MDEV_RENAME)
unlink(device_name);
//创建设备节点
if (mknod(device_name, mode | type, makedev(major, minor)) && errno != EEXIST)
bb_perror_msg_and_die("mknod %s", device_name);
if (major == root_major && minor == root_minor)
symlink(device_name, "root");
#if ENABLE_FEATURE_MDEV_CONF
chown(device_name, ugid.uid, ugid.gid);
#if ENABLE_FEATURE_MDEV_RENAME
if (alias) {
alias = build_alias(alias, device_name);
if (rename(device_name, alias) == 0 && aliaslink == '>')
symlink(alias, device_name);
free(alias);
}
#endif
#endif
}
...
}
从上面的代码分析到,要使用mdev.conf配置文件,还需要配置busybox的menuconfig,使mdev支持mdev.conf选项才行。进入busybox目录,make menuconfig
Linux System Utilities --->
[*] Support /etc/mdev.conf
2 U盘自动挂载
vi /etc/mdev.conf
添加
sda[1-9]+ 0:0 660 * if [ $ACTION = "add" ]; then mount /dev/$MDEV /mnt; else umount /mnt; fi
插入U盘,查看ls -l /dev/sda*、ls /mnt