I have an assignment to build support for distributed mutual exclusion using raymond's algorithm in freebsd.
This requires a kernel thread to always listen on a udp port for messages from other systems and act accordingly.
I'm creating a thread using thread_create, but inside every call to socreate creates a kernel panic. What's the best way to do what I'm doing? I couldn't find any good tutorials on kernel networking in freebsd.
On another note, maybe the mainproc
variable is not set correctly. How can I find out current struct proc*
or struct thread*开发者_开发问答
?
My current code is like this:
static struct proc *mainproc;
static int val;
static int main_thread_finish;
static struct socket *listenso;
static struct sockaddr_in listenadr;
static void main_thread(void* data)
{
static int res;
printf("In thread\n");
res = socreate(AF_INET, &listenso, SOCK_DGRAM, IPPROTO_UDP, mainproc->p_ucred, mainproc->p_singlethread);
printf("socreate res: %d\n", res);
listenadr.sin_family = AF_INET;
listenadr.sin_port = htons(1234);
listenadr.sin_addr.s_addr = 0;
res = sobind(listenso, (struct sockaddr*)&listenadr, mainproc->p_singlethread);
printf("bind res: %d\n", res);
while(!main_thread_finish)
{
pause("DUMMY", hz);
}
printf("kthread exiting...\n");
kthread_exit();
}
static int
raymond_module_load(struct module *module, int cmd, void *arg)
{
int error = 0;
switch (cmd) {
case MOD_LOAD :
val = 12345;
main_thread_finish = 0;
kproc_create(main_thread, NULL, &mainproc, 0, 0, "raymond_main_thread");
printf("Module loaded - kthread created\n");
break;
case MOD_UNLOAD :
main_thread_finish = 1;
printf("Waiting for thread to exit...\n");
pause("TWAIT", 3*hz);
printf("Module unload...\n");
break;
default :
error = EOPNOTSUPP;
break;
}
return (error);
}
static moduledata_t raymond_module_data = {
.name = "raymond_module",
.evhand = raymond_module_load,
.priv = NULL };
DECLARE_MODULE(raymond_module, raymond_module_data, SI_SUB_KLD, SI_ORDER_ANY);
The call to socreate
panics because mainproc->p_singlethread
is NULL
. This variable is not the thread associated with the process but is used to enforce "single-threading" within a process (see the function thread_single()
in sys/kern/kern_thread.c
for more details).
Probably what you wanted to do was was to use curthread
res = socreate(AF_INET, &listenso, SOCK_DGRAM, IPPROTO_UDP,
curthread->td_ucred, curthread);
...
res = sobind(listenso, (struct sockaddr*)&listenadr, curthread);
Consider using netgraph, it has ready to use ng_ksocket module.
精彩评论