Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

linux dlopen: can a library be "notified" when it is loaded?

Is there a way for a shared library to be "notified" when it is loaded?

In other words, let's say I use dlopen on a shared library, is there a function that is automatically called (if present) on the shared library (e.g. main?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Libraries should export initialization and cleanup routines using the gcc __attribute__((constructor)) and __attribute__((destructor)) function attributes. See the gcc info pages for information on these. Constructor routines are executed before dlopen returns (or before main() is started if the library is loaded at load time). Destructor routines are executed before dlclose returns (or after exit() or completion of main() if the library is loaded at load time). The C prototypes for these functions are:

 void __attribute__ ((constructor))  my_init(void);  
 void __attribute__  ((destructor)) my_fini(void);

Taken from http://tldp.org/HOWTO/Program-Library-HOWTO/index.html

THat is, you just tack on __attribute__ ((constructor)) to the functions you want to be called when the shared library is loaded. The above docuemtn also notes that the older _ini and _fini functions are considered obsolete.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...