简体   繁体   English

dlopen之后使用fork

[英]Using fork after dlopen

I used dlopen to load a dynamic link library (.so) in my program, called dlsym to get the address to a certain function foo . 我使用dlopen在程序中加载了名为dlsym的动态链接库(.so),以获取特定函数foo的地址。

Then I used fork and called foo in the sub-process, and used exit(0) to exit the sub-process. 然后,我在子进程中使用fork并调用了foo ,并使用exit(0)退出了子进程。 Till now, everything is alright. 到现在为止,一切都很好。

And when I tried to fork and call foo again in the sub-process, I found that all data stored by static variables defined in foo was lost. 当我尝试在子流程中再次fork并调用foo时,我发现foo中定义的静态变量存储的所有数据都丢失了。 I am sure that I didn't call functions like dlclose explicitly. 我确定我没有显式调用dlclose函数。 So how can I prevent the data from disappearing? 那么如何防止数据消失呢?

Thanks a lot. 非常感谢。

You want shared memory. 您要共享内存。 See How to use shared memory with Linux in C for some introductory pointers. 有关一些入门指针,请参见如何在C语言中的Linux中使用共享内存 Be forewarned, however, that synchronization is tricky and you will probably end up wanting a higher-level abstraction, like message-passing or semaphores. 但是请注意,同步是棘手的​​,您可能最终会需要更高级别的抽象,例如消息传递或信号量。

(Alternatively, maybe forking isn't the model you're looking for. Threads are literally the concept of having multiple execution paths using the same process-memory space...) (或者,叉不是您想要的模型。线程实际上是使用相同的进程内存空间具有多个执行路径的概念。)

fork ing your program has the effect of duplicating its address space, including the storage for foo 's static locals. 对程序进行fork具有复制其地址空间的作用,包括存储foo的静态本地变量。 It's that copy that was initialized in the child process by the call to foo . 就是在子进程中通过调用foo初始化的副本。

It is no surprise, then, that the original storage is unchanged, as you can see from the second fork and call to foo on a second copy of that uninitialized storage. 因此,原始存储没有更改也就不足为奇了,正如您从第二个fork看到的那样,在该未初始化存储的第二个副本上调用foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM