简体   繁体   中英

Thread lifetime in linux

Currently I'm trying to understand what happens when a shared library spawns a thread, which does not terminate and the shared library is then unloaded.

What happens to the thread if the parent does not wait for the thread to exit? Does the thread die or does it remain in the running state?

If it does then how can the parent detect when it's being unloaded and somehow terminate the thread?

Thanks for any help.

I assume the shared library is some plugin dynamically loaded at runtime using dlopen(3) and later explicitly unloaded using dlclose .

The dlopen and dlclose functions are internally using a reference counter and they are mmap(2) -ing (for dlopen ) and munmap -ing (for dlclose ) some segments inside the ELF shared object when appropriate (ie when the ref counter crosses the 0 border).

If a thread is running some function inside the dlclose -d shared library, the code of that function becomes munmap -ed and as soon as you jump (or return into) that function, you get a SIGBUS, SIGILL or SIGSEGV signal.

So you don't want that munmap to happen: hence you could:

  1. avoid calling dlclose ; this works very well in practice (unless you have a server program), because mmap consumes mostly address space for text read-only segments of shared object. As my manydl.c demonstrates, you can dlopen hundreds of thousands of shared objects on a desktop without reaching serious limits.

  2. or pass RTLD_NODELETE to dlopen asking it to never unmap the library

Alternatively, use some facilities (ie destructor -attributed functions in the shared library) or conventions (perhaps atexit(3) ?) to be sure that the thread has ended before dlclose

Shared library is loaded into process, so spawn thread will run in process address space.

Thread will keep running if not noticed to exit. and when process is exit, thread will also be terminated.

As shared library spawn the thread, so it is better that shared library also provide a function which will notice thread to exit so process can call the function to exit thread before unload library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM