GB | BIG5
|
| 首頁 > 編程技術 > C/C++ > 正文 |
 |
| Solaris下如何使用LD_PRELOAD環境變量 |
| 本文出自:http://www.xici.net 作者: (2001-07-30 12:00:00) |
by scz (小四)
下面即將演示如何利用LD_PRELOAD環境變量影響標準I/O庫函數printf(3S)。環境變
量LD_PRELOAD的值是whitespace-separated的共享庫列表,運行時鏈接器負責解釋它。
由LD_PRELOAD指定的共享庫優其他共享庫加載。
--------------------------------------------------------------------------
/* main.c */
#include
#include
int main ( int argc, char * argv[] )
{
char s[] = "Hello World\n";
printf( s );
return( EXIT_SUCCESS );
}
--------------------------------------------------------------------------
--------------------------------------------------------------------------
/* mylib.c */
#include
#include
int printf ( char * s )
{
char *t = s;
while ( *s )
{
*s = toupper( *s ), s++;
}
return( ( int )write( 0, t, strlen( t ) ) );
}
--------------------------------------------------------------------------
--------------------------------------------------------------------------
# Makefile
CC="/opt/SUNWspro/SC5.0/bin/cc"
all: a.out
mylib.so: mylib.c
${CC} -g -G -o mylib.so mylib.c
a.out: main.c mylib.so
${CC} -g main.c
clean:
rm -rf mylib.so mylib.o a.out *~
--------------------------------------------------------------------------
[scz@ /export/home/scz/src]> sotruss ./a.out
a.out -> libc.so.1:*atexit(0xff3b9c6c, 0x20800, 0x0)
a.out -> libc.so.1:*atexit(0x109f0, 0xff3b9c6c, 0xff235e68)
a.out -> libc.so.1:*printf(0xffbefa47, 0xff239c1c, 0xff235e60)
Hello World
a.out -> libc.so.1:*exit(0x0, 0xffbefabc, 0xffbefac4)
[scz@ /export/home/scz/src]>
注意到來自動態鏈接庫"libc.so.1"的庫函數printf()在"a.out"中被調用。現在,如
果你想使用來自"mylib.so"的printf()函數,利用LD_PRELOAD環境變量通知運行時鏈
接器優先使用"mylib.so"解析未知符號。
[scz@ /export/home/scz/src]> LD_PRELOAD=./mylib.so ./a.out
HELLO WORLD
[scz@ /export/home/scz/src]>
為了解釋更清楚些,再次使用sotruss(1)命令
[scz@ /export/home/scz/src]> LD_PRELOAD=./mylib.so sotruss ./a.out
a.out -> libc.so.1:*atexit(0xff3b9c6c, 0x20800, 0x0)
a.out -> libc.so.1:*atexit(0x109f0, 0xff3b9c6c, 0xff235e68)
a.out -> mylib.so:*printf(0xffbefa27, 0xff239c1c, 0xff235e60)
HELLO WORLD
a.out -> libc.so.1:*exit(0x0, 0xffbefa9c, 0xffbefaa4)
[scz@ /export/home/scz/src]>
如你所見,運行時鏈接器現在使用了來自動態鏈接庫"mylib.so"的printf()函數。
(http://www.fanqiang.com)
進入【UNIX論壇】
|
|
| 相關文章 |
|
|
|
|
 |
★ 樊強制作 歡迎分享 ★ |