Re: Kernel thread removal

From: linux-os (Dick Johnson)
Date: Wed Feb 22 2006 - 12:43:50 EST



On Wed, 22 Feb 2006, James Yu wrote:

> How do I remove a kernel thread in kernel mode ?
> I write a C-function in one of the Linux source files and create a
> kernel thread by invoking kernel_thread() to run the function, like:
> "kernel_thread(a1, NULL, CLONE_FS | CLONE_FILES | CLONE_SIGNAL);"
> Function a1 simply invokes printk() to output some message on console.
> I invoke do_exit(0); at the end of a1, but a1's task_struct still
> exists in in task_struct list after its execution.
> How do I remove it a1's task_struct upon its completion? I thought
> explicitly invoke do_exit() ensures the removal of task_struct?
> -

This is becoming a FAQ. In the main loop that your kernel thread
executes, you do:

if(signal_pending(current))
complete_and_exit(&struct_completion, status_value);


In the module exit code, or wherever you want to shut down the
kernel thread, you do:

kill_proc(thread_pid, some_unblocked_signal, 1);
wait_for_completion(&struct_completion);

Remember to do init_completion(&struct_completion) in the startup
code, and to unblock the signal the kernel thread is supposed to
receive, SIGTERM is a good one.

The secret of success is that the kernel thread needs to
exit in the context of the kernel thread, and somebody needs to
pick up its status. Re-parenting to `init` will not always
work for reaping child status because `init` needs to get the
CPU at the time that you, in the module-remove routine, may
have the CPU. This might deadlock. The solution is above.

A final word, both complete_and_exit() and wait_for_completion()
need to be free of any spin-locks.

Cheers,
Dick Johnson
Penguin : Linux version 2.6.15.4 on an i686 machine (5589.54 BogoMips).
Warning : 98.36% of all statistics are fiction.
_


****************************************************************
The information transmitted in this message is confidential and may be privileged. Any review, retransmission, dissemination, or other use of this information by persons or entities other than the intended recipient is prohibited. If you are not the intended recipient, please notify Analogic Corporation immediately - by replying to this message or by sending an email to DeliveryErrors@xxxxxxxxxxxx - and destroy all copies of this information, including any attachments, without reading or disclosing them.

Thank you.
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/