我正在尝试编写一个使用 linux 看门狗驱动程序 ping 看门狗设备的服务。在名为“LoadConfigurationFile”的函数中,我传递了一个指向上面定义的结构的指针。然后,该函数通过库调用(libconfig)获取一个字符串并将其存储在结构中变量的地址中。但是,当我访问变量 'printf("%s\n", options.devicepath);return 1;' 而不是按预期打印配置文件的内容:“/dev/watchdog”,程序显示“�/watchdog”。
#include <errno.h>
#include <getopt.h>
#include <limits.h>
#include <linux/types.h>
#include <linux/watchdog.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <syslog.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <libconfig.h>
struct cfgoptions {
const char* devicepath;
};
struct cfgoptions options;
char *confile = "/etc/watchdogd.cfg";
int LoadConfigurationFile(struct cfgoptions *s);
int main(int argc, char *argv[])
{
struct cfgoptions *st_ptr;
st_ptr = &options;
if (LoadConfigurationFile(st_ptr) < 0)
/*exit(EXIT_FAILURE);*/
/**/
printf("%s\n", options.devicepath);return 1;
/**/
int LoadConfigurationFile(struct cfgoptions *s)
{
config_t cfg;
config_init(&cfg);
if (!config_read_file(&cfg, confile) && config_error_file(&cfg) == NULL)
{
fprintf(stderr, "daemon: cannot open configuration file: %s\n", config_error_file(&cfg));
config_destroy(&cfg);
return -1;
} else if (!config_read_file(&cfg, confile)) {
fprintf(stderr, "daemon:%s:%d: %s\n", config_error_file(&cfg), config_error_line(&cfg), config_error_text(&cfg));
config_destroy(&cfg);
config_destroy(&cfg);
return -1;
}
if (!config_lookup_string(&cfg, "watchdog-device", &s->devicepath))
s->devicepath = "/dev/watchdog";
config_destroy(&cfg);
return 0;
}
/etc/watchdogd.cfg:
看门狗设备 = "/dev/看门狗"
int config_setting_lookup_string(const config_setting_t *setting,
const char *name, const char **value)
{
config_setting_t *member = config_setting_get_member(setting, name);
if(! member)
return(CONFIG_FALSE);
if(config_setting_type(member) != CONFIG_TYPE_STRING)
return(CONFIG_FALSE);
*value = config_setting_get_string(member);
return(CONFIG_TRUE);
}
config_setting_t *config_setting_get_member(const config_setting_t *setting,
const char *name)
{
if(setting->type != CONFIG_TYPE_GROUP)
return(NULL);
return(__config_list_search(setting->value.list, name, NULL));
}
const char *config_setting_get_string(const config_setting_t *setting)
{
return((setting->type == CONFIG_TYPE_STRING) ? setting->value.sval : NULL);
}