我正在使用 libiptc 通过自定义 c 程序执行 iptables 更新。要求是每 2 秒从一个单独的线程调用 iptc API。
我编写了一个简单的 C 程序来尝试从单独的线程调用 iptc API。c程序粘贴在下面。
/*** thread_iptc.c ***/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void* thread_func(void* unused)
{
struct iptc_handle *handle = NULL;
char *table = "filter";
while (1)
{
printf("\nthread_func(): While loop.\n");
handle = iptc_init(table);
if (handle) {
printf("thread_func(): handle is not NULL.\n");
iptc_free(handle);
}
else
printf("thread_func(): handle is NULL.\n");
sleep(2);
}
return NULL;
}
int main()
{
struct iptc_handle *handle = NULL;
char *table = "filter";
pthread_t thread_id;
handle = iptc_init(table);
if (handle) {
printf("main(): handle is not NULL.\n");
iptc_free(handle);
}
else
printf("main(): handle is NULL.\n");
pthread_create(&thread_id, NULL, &thread_func, NULL);
pthread_join(thread_id, NULL);
return 0;
}
我面临的问题是对两者的调用iptc_init(
)并且从函数iptc_free()
调用时效果很好。main
但是,iptc_free()
从 调用时,调用失败并出现“分段错误” thread_func()
。
程序输出:
# ./test
main(): handle is not NULL.
thread_func(): While loop.
thread_func(): handle is not NULL.
Segmentation fault
汇编:
# gcc -o test thread_iptc.c -lpthread -lext4 -lext6 -lip4tc -lip6tc -liptc -lxtables -ldl
GDB 回溯
#0 0x00007ffff79be303 in iptc_free () from /lib64/libip4tc.so.0
#1 0x00000000004007f3 in thread_func ()
#2 0x00007ffff7bc77e1 in start_thread () from /lib64/libpthread.so.0
#3 0x00007ffff6efb8ed in clone () from /lib64/libc.so.6
在编译期间或调用新线程时我是否遗漏了什么?