I am working on performing iptables update through a custom c program using libiptc. The requirement is to invoke iptc APIs from a separate thread every 2 seconds.
I have written a simple C program to try out invoking of iptc APIs from a separate thread. The c program is pasted below.
/*** 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;
}
The problem, I am facing is that call to both iptc_init(
) and iptc_free()
works well when called from main
function. However, call to iptc_free()
fails with "Segmentation Fault" when called from thread_func()
.
Program Output:
# ./test
main(): handle is not NULL.
thread_func(): While loop.
thread_func(): handle is not NULL.
Segmentation fault
Compilation:
# gcc -o test thread_iptc.c -lpthread -lext4 -lext6 -lip4tc -lip6tc -liptc -lxtables -ldl
GDB Backtrace
#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
Am I missing something during compilation or while invoking a new thread?