可以使用 3种方法与多个进程共享对象,这 3种方法是:
1,句柄继承性、
2,句柄命名、
3,句柄复制。
[句柄:指内核对象的句柄]
也可通过在dll里设置数据段来共享变量:
//Tell the compiler to put this initialized variable in its own Shared
//section so it is shared by all instances of this application.
#pragma data_seg("Shared")
volatile LONG g_lApplicationInstances = 0;
#pragma data_seg()
//Tell the linker to make the Shared section readable,writable,and shared.
#pragma comment(linker,"/Section:Shared,RWS")
Microsoft 的Visual C++编译器提供了一个A l l o c a t e说明
入你希望的任何节中。请看下面的代码:
Create Shared setion & have compiler place initialized data in it.
#pragma data_seg("Shared")
//Initialized, in Shared section
int a = 0;
//Uninitialized, not in Shared section
int b;
//Have compiler stop placing initialized data in Shared section.
#pragma data_seg()
//Initialized , in Shared section
_ _declspec(allocate("Shared')) int c = 0;
//Uninitialized , in Shared section
_ _declspec(allocate("Shared')) int d;
//Initialized, not in Shared section
int e = 0;
//Uninitialized, not in Shared section
int f;
虽然可以创建共享节,但是,由于两个原因,M i c r o s o f t并不鼓励你使用共享节。第一,用
这种方法共享内存有可能破坏系统的安全。第二,共享变量意味着一个应用程序中的错误可能
影响另一个应用程序的运行,因为它没有办法防止某个应用程序将数据随机写入一个数据块。
假设你编写了两个应用程序,每个应用程序都要求用户输入一个口令。然而你又决定给应
用程序添加一些特性,使用户操作起来更加方便些:如果在第二个应用程序启动运行时,用户
正在运行其中的一个应用程序,那么第二个应用程序就可以查看共享内存的内容,以便获得用
户的口令。这样,如果程序中的某一个已经被使用,那么用户就不必重新输入他的口令。
这听起来没有什么问题。毕竟没有别的应用程序而只有你自己的应用程序加载了 D L L,并
且知道到什么地方去查找包含在共享节中的口令。但是,黑客正在窥视着你的行动,如果他们
想要得到你的口令,只需要编写一段很短的程序,加载到你的公司的 D L L文件中,然后监控共
享内存块。当用户输入口令时,黑客的程序就能知道该用户的口令。
黑客精心编制的程序也可能试图反复猜测用户的口令并将它们写入共享内存。一旦该程序
猜测到正确的口令,它就能够将各种命令发送给两个应用程序中的一个。如果有一种办法只为
某些应用程序赋予访问权,以便加载一个特定的D L L,那么这个问题也许是可以解决的。但是
目前还不行,因为任何程序都能够调用L o a d L i b r a r y函数来显式加载D L L。