Catching the return of main function before it deallocates resources

Posted by EpsilonVector on Stack Overflow See other posts from Stack Overflow or by EpsilonVector
Published on 2010-05-18T21:22:19Z Indexed on 2010/05/19 2:10 UTC
Read the original article Hit count: 205

Filed under:
|
|

I'm trying to implement user threads in Linux kernel 2.4, and I ran into something problematic and unexpected.

Background: a thread basically executes a single function and dies, except that when I call thread_create for the first time it must turn main() into a thread as well (by default it is not a thread until the first call, which is also when all the related data structures are allocated).

Since a thread executes a function and dies, we don't need to "return" anywhere with it, but we do need to save the return value to be reclaimed later with thread_join, so the hack I came up with was: when I allocate the thread stack I place a return address that points to a thread_return_handler function, which deallocates the thread, makes it a zombie, and saves its return value for later. This works for "just run a function and die" threads, but is very problematic with the main thread. Since it actually is the main function, if it returns before the other threads finish the normal return mechanism kicks in, and deallocates all the shared resources, thus screwing up all the running threads.

I need to keep it from doing that. Any ideas on how it can be done?

© Stack Overflow or respective owner

Related posts about linux-kernel

Related posts about threads