[TriLUG] shared libraries aren't shared
Joseph Mack NA3T
jmack at wm7d.net
Wed Nov 11 14:55:27 EST 2009
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
--
Joseph Mack NA3T EME(B,D), FM05lw North Carolina
jmack (at) wm7d (dot) net - azimuthal equidistant map
generator at http://www.wm7d.net/azproj.shtml
Homepage http://www.austintek.com/ It's GNU/Linux!
More information about the TriLUG
mailing list