views:

81

answers:

1

What are the main differences between binding to a shared object or to an ordinary object? Also how is this possible to share some variables between some programs and knowing that our variables are never changed by another program?

+2  A: 

Variables are not shared between programs, ever. (Although specially-allocated shared memory can be shared, this is an "object" and not a "variable" in C terminology.) Where you're confused is that the on-disk backing is what's shared between processes, and this is the same whether it's the main program (static or dynamic linked) or a shared library file. The operating system's virtual memory implementation takes care of using the same page of physical memory for multiple processes when the contents are unchanged from what's on-disk, and making physical duplicates of pages at runtime if they're written to. All of this is transparent to your application, which sees a linear 32- or 64-bit address space consisting of nothing but its own code and data.

In practice, the dynamic linking system makes a number of storage optimizations which isolate the data which will be changed per-process to a few pages, allowing the vast majority of pages to be shared between processes that use the same executable file or same libraries.

R..
Thanks for your answer, if i got your answer right then the variables are first shared and then if a process wants to change them they are mapped into the processes adress space. right?
Green Code
We need to be careful when we say the variables are shared. The shared object can have variables in it. The process that uses that shared library will have its own copy of the variable. I.E. prog-A and prog-B can both use the same shared library. They will booth have copies of the variable foo from the shared library, but prog-A's foo is different from prog-B's foo.
John Rocha
Having said the above, there is also the concept of shared memory. Shared memory can be created and used by any process, with or without shared objects. They are different concepts that have "shared" in their names. Shared memory is essentially a named memory region that processes can map into their virtual address space. Shared memory can be used to actually share variables between two different processes.
John Rocha
I addressed shared memory in my answer, and as you'll see if you read it, I already pointed out that data in shared memory is not "variables" but "objects". In the C language, a *variable* has a name and scope and is defined in the source file. Objects obtained by `malloc` (and similarly any implementation-specific allocation function) are not variables, but it's likely that you'll store their addresses in *pointer variables*.
R..