关于C中的多处理和静态变量的问题
我在 C 项目中遇到一些问题。 情况如下:
- 我有一个主文件,其中包括一个带有静态变量的文件 .h 和另一个带有所有函数的 C 文件(这也包括文件 .h)。
- 如果我运行 main 它工作正常,但我想在不同的 shell 上运行不同的实例,以便我可以交换消息。
问题是两个进程都在内存的同一位置分配静态变量,因此第二个实例完成的操作将覆盖第一个实例的操作。
希望我说得清楚,我对C不太精通。
I am having some problem with a C project.
The situation is the following:
- I have a main file which includes a file .h with static variables and another C file with all the functions (this also includes the file .h).
- If I run the main it works fine, but I would like to run different instances on different shells so that I can exchange messages.
The problem is that both the processes are allocating the static variables in the same location of memory, so the operations done by the second instance will overwrite the ones of the first instance.
Hope I was clear, I'm not very proficient in C.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能使用静态变量在两个进程之间交换数据。您看到的地址很可能是虚拟,即每个进程都有自己的地址空间,因此,尽管地址可能看起来相同,但它实际上映射到不同的 RAM。
你需要一个真正的进程间通信(IPC)解决方案,比如文件、共享内存、管道、套接字或类似方法。
You can't use a static variable to exchange data between two processes. The addresses you are seeing are very likely to be virtual, i.e. each process has its own address space, so although an address might look identical, it's really mapped to different RAM.
You need a real inter-process communication (IPC) solution, such as files, shared memory, pipes, sockets, or similar approach.
事实并非如此。每个进程都有自己完全独立的地址空间,因此它们不能互相覆盖。
That isn't so. Each process gets its own completely separate address space, so they cannot overwrite each other.