如何使用tdb多写入器 同进程打开多tdb连接段错误排查
问题原因与解决方法
段错误的直接诱因
你观察到的段错误和多连接本身无关,是错误处理逻辑的bug:第二次调用tdb_open失败返回空指针时,你直接将空指针传入了tdb_errorstr(),该函数内部没有空指针校验,会直接访问结构体成员触发非法内存访问。
注意只有tdb_open返回非空的有效上下文指针时,才能调用tdb_errorstr();如果返回空,应该直接用strerror(errno)打印系统错误信息。
多连接打开失败的原因
tdb默认禁止同一个进程内对同一个数据库文件打开多个上下文,官方文档中提到的多写入器支持默认针对跨进程场景,同进程内打开多个连接需要额外配置标志位。
你代码中tdb_open的第三个参数(tdb专属标志位)传了0,没有开启同进程多开许可,所以第二次打开会被直接拒绝。
要支持同一进程多个读写连接,需要在第三个参数中加上TDB_MULTIOPEN标志。
修改后的可运行代码
#include <stdio.h> #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #include <tdb.h> int main(int argc, char** argv) { struct tdb_context * tdb = tdb_open("test.tdb", 0, TDB_MULTIOPEN, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP); if(!tdb){ printf("First open failed: %s\n", strerror(errno)); return 1; } else { printf("Database successfully opened!\n"); } struct tdb_context * anothertdb = tdb_open("test.tdb", 0, TDB_MULTIOPEN, O_RDWR| O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP); if(!anothertdb){ printf("Second open failed: %s\n", strerror(errno)); tdb_close(tdb); return 1; } else { printf("Another writer successfully opened!\n"); } if(tdb_close(anothertdb)){ printf("Error while closing anothertdb: %s\n", tdb_errorstr(anothertdb)); } else { printf("closing anothertdb-connection\n"); } if(tdb_close(tdb)){ printf("Error while closing tdb: %s\n", tdb_errorstr(tdb)); } else { printf("closing tdb-connection\n"); } return 0; }
编译运行后会输出正常的打开、关闭日志,不会出现崩溃或打开失败的问题。
内容的提问来源于stack exchange,提问作者Keya Kersting
相关产品推荐
相关产品推荐

