我正在尝试编写一个使用linux看门狗驱动程序ping看门狗设备的服务。
在名为“LoadConfigurationFile”的函数中,我将指针传递给上面定义的结构。然后,该函数获取一个字符串,并使用库调用(libconfig)将其存储在结构中变量的地址处。
但是,当我访问变量'printf(“%s\n”,options.devicepath);返回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:
watchdog-device =“/dev/watchdog”
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);
}
最佳答案
问题是您正在调用config_destroy。这将丢失您在查找期间分配的所有数据。
—功能:void config_destroy(config_t * config)
这些函数初始化并破坏配置对象config。
config_init()将config指向的config_t结构初始化为新的空配置。
config_destroy()破坏配置config,释放与该配置关联的所有内存,但不尝试释放config_t结构本身。
对此很确定。
尝试摆脱那条线,看看会发生什么。
更多:libconfig在为传入的指针分配内存时,必须将内存引用保留在某个地方,以便以后可以清理它们。这就是cfg对象。对于库分配的所有内容来说,这只是一个大记录对象。销毁它时,该库必须释放所有分配的内存,否则它将永远泄漏。
关于c - 使用库函数存储值时,结构中的变量损坏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17439367/