[TriLUG] shared libraries aren't shared

David Both dboth at millennium-technology.com
Wed Nov 11 15:05:33 EST 2009


My understanding is that the code is shared but that the values of the variables are separate instances. This would be required for reentrant code. You would have to overtly share the memory belonging to a variable to have both instances of the code show the same value.

-- 


*********************************************************
David P. Both, RHCE
Millennium Technology Consulting LLC
919-389-8678

dboth at millennium-technology.com

www.millennium-technology.com 
www.databook.bz - Home of the DataBook for Linux
DataBook is a Registered Trademark of David Both



On Wednesday 11 November 2009 14:55:27 Joseph Mack NA3T wrote:
> I'm noodling around with shared libraries. AFAIK, if two 
> executables are running simultaneously on a machine and they 
> both use the same shared library, then there should be only 
> one copy of the shared library in memory. In that case I 
> should be able to show a race condition with a global 
> variable in the shared library.
> 
> Here's my main()
> 
> //main.c
> 
> void print_int(int);
> 
> int main() {
>          int i = 10;
>          print_int(i);
>          sleep (5);
>          print_int(i);
>          return (0);
> }
> //-main.c-------------------
> 
> 
> Here's the source code for the shared library
> 
> //print_int.c
> 
> #include <stdio.h>
> 
> int j = 0;	//global variable
> 
> void print_int(int x) {
>          printf ("%d \n", x);
>          ++j;	//increment global variable
>          printf ("j=%d \n", j);
> }
> //-print_int.c--------------------
> 
> Each time print_int() is called, it will increment j.
> 
> Here's my compile
> 
> gcc -c -Wall -fPIC  print_int.c -o print_int.o
> gcc -shared -Wl,-soname,libmy_function.so.2.0 -o libmy_function.so.2.0.1 print_int.o
> cp -pauv libmy_function.so.2.0.1 /usr/lib
> ldconfig
> 
> gcc -c -Wall -fPIC  main.c -o main.o
> gcc -Wall -o my_function.dynamic main.o libmy_function.so.2.0.1
> cp -pauv my_function.dynamic /usr/bin/my_function
> 
> ldd shows that the executable is dynamically linked to the 
> shared library.
> 
> I would have thought that I'd at least get a warning about 
> the global variable in a shared library, but gcc is fine 
> with it.
> 
> Here's a single copy of the code running, showing the global 
> variable being incremented
> 
> my_function# my_function
> 10
> j=1
> 10
> j=2
> 
> Now I run two copies of the executable, in two windows. With 
> 10secs of sleep in main(), there will be time to start both 
> processes and have them running at the same time. I would 
> expect one of the outputs to show j=3, but both processes 
> behave as if they have their own copy of the shared library.
> 
> Any ideas? Why doesn't the shared library behave as if it's 
> shared? How can I tell if there is only one copy of the 
> shared library in memory?
> 
> Thanks Joe
> 
> 



More information about the TriLUG mailing list