首页 > 编程开发 > C/C++ > 正文  
Solaris下如何使用LD_PRELOAD环境变量
出自:http://www.xici.net 2002年01月08日 14:03
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 ";

  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
-g -G -o mylib.so mylib.c

a.out: main.c mylib.so
-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.trainlinux.com】【Close
『相关资料』
linux系统调用实现代码分析 (2002-01-08 14:02)
Unix(Linux) C编程问题精粹 (2002-01-08 14:02)
解析C语言中的sizeof (2002-01-08 14:02)
Linux下的多进程编程 (2002-01-07 14:01)
Home 

诚恩Linux培训工作室