当前位置:早雪网网络学院编程文档C/C++ → Solaris下如何使用LD_PRELOAD环境变量

Solaris下如何使用LD_PRELOAD环境变量

减小字体 增大字体 作者:不详  来源:supcode.com收集整理  发布时间:2005-7-22 19:38:15
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()函数。

Tags:Solaris,如何,使用,LD,PRELOAD,环境,变量
[数据载入中...] [返回上一页] [打 印]