grub2中env绑定hook函数
2019-11-09 16:20:04
供稿:网友
在调用grub_env_get 获取环境变量的时候,可以对这个环境变量绑定一个处理函数。grub_env_get (const char *name){ struct grub_env_var *var; var = grub_env_find (name); if (! var) return 0; if (var->read_hook) return var->read_hook (var, var->value); return var->value;}例如grub_env_get 中如果通过grub_env_find 找到这个env的话,会判断是否绑定read_hook 函数,如果绑定就返回read_hook。这个感觉和grub_register_command 有一曲通过的效果。static const char *grub_datetime_names[] ={ "YEAR", "MONTH", "DAY", "HOUR", "MINUTE", "SECOND", "WEEKDAY",};GRUB_MOD_INIT(datehook){ unsigned i; for (i = 0; i < ARRAY_SIZE (grub_datetime_names); i++) { grub_register_variable_hook (grub_datetime_names[i], grub_read_hook_datetime, 0); grub_env_export (grub_datetime_names[i]); }}这个例子会对注册在grub_datetime_names 中的每一个字符串绑定一个grub_read_hook_datetime 函数,这样当调用grub_get_env("YEAR")的时候就会调用grub_read_hook_datetime函数grub_read_hook_datetime (struct grub_env_var *var, const char *val __attribute__ ((unused))){ struct grub_datetime datetime; static char buf[6]; buf[0] = 0; if (! grub_get_datetime (&datetime)) { int i; for (i = 0; i < 7; i++) if (grub_strcmp (var->name, grub_datetime_names[i]) == 0) { int n; switch (i) { case 0: n = datetime.year; break; } return buf;}grub_read_hook_datetime的实现也很简单,就是返回具体对应的时间.grub_register_variable_hook (const char *name, grub_env_read_hook_t read_hook, grub_env_write_hook_t write_hook){ struct grub_env_var *var = grub_env_find (name); if (! var) { if (grub_env_set (name, "") != GRUB_ERR_NONE) return grub_errno; var = grub_env_find (name); /* XXX Insert an assertion? */ } var->read_hook = read_hook; var->write_hook = write_hook; return GRUB_ERR_NONE;}而grub_register_variable_hook 则首先通过grub_env_find 找到这个env,如果没有找到则不绑定,也就是说在调用grub_register_variable_hook 之前必须调用grub_env_set 函数先设定环境变量.