访问全局变量以修改值
Access to the global variable to modify the value
我有一个带有全局变量(如extern double variable
)的c++程序
当另一个c++程序运行该变量时,我想更改该变量的值
如何通过其他程序访问该变量并更改值?
例如:
#include <iostream>
extern double myvariable = 0.0;
int main() {
//waiting for modify value by another programs
while (myvariable == 0.0)
{
}
cout << myvariable << endl;
return 0;
}
我需要另一个程序中的函数来修改myvariable
的值。
从Boost::interprocess开始。您需要在两个进程中创建命名共享内存,并将变量存储在该空间中。这将允许两个进程访问变量。
在父进程中:
//Construct managed shared memory
managed_shared_memory segment(create_only, "MySharedMemory", 65536);
//Create an object of MyType initialized to {0.0, 0}
MyType *instance = segment.construct<MyType>
("MyType instance") //name of the object
(0.0, 0); //ctor first argument
在子进程中:
managed_shared_memory segment(open_only, "MySharedMemory");
std::pair<MyType*, managed_shared_memory::size_type> res;
//Find the object
res = segment.find<MyType> ("MyType instance");
//Length should be 1
if(res.second != 1) return 1;
这是服务器进程:
#include <boost/interprocess/windows_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#include <cstring>
int main ()
{
using namespace boost::interprocess;
try{
//Create a native windows shared memory object.
windows_shared_memory shm (create_only, "shared_memory", read_write, 1000);
//Map the whole shared memory in this process
mapped_region region(shm, read_write);
//Write all the memory to 1
std::memset(region.get_address(), 1, 1000);
//Launch the client process and wait until finishes...
//...
}
catch(interprocess_exception &ex){
std::cout << ex.what() << std::endl;
return 1;
}
return 0;
}
现在,在销毁windows_shared内存对象之前,启动客户端进程:
#include <boost/interprocess/windows_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#include <cstring>
int main ()
{
using namespace boost::interprocess;
try{
//Open already created shared memory object.
windows_shared_memory shm(open_only, "shared_memory", read_only);
//Map the whole shared memory in this process
mapped_region region (shm, read_only);
//Check that memory was initialized to 1
const char *mem = static_cast<char*>(region.get_address());
for(std::size_t i = 0; i < 1000; ++i){
if(*mem++ != 1){
std::cout << "Error checking memory!" << std::endl;
return 1;
}
}
std::cout << "Test successful!" << std::endl;
}
catch(interprocess_exception &ex){
std::cout << "Unexpected exception: " << ex.what() << std::endl;
return 1;
}
return 0;
}
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 当vector是tje全局变量时,c++中vector的内存管理
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 内联函数中具有内部链接的全局变量
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 全局变量 多读取器 一个写入器多线程安全?
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 不同作用域中的静态变量和全局变量
- C++ 在编译时具有函数计算全局变量
- 修改程序的入口点时未调用全局变量的构造函数
- 使用 std::ios_base::Init 正确初始化全局变量
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 在 C++17 中修改 constexpr 函数中的全局变量
- 避免使用大量全局变量或使其易于访问和修改的最佳方法
- 可修改全局变量c++
- C++:无法修改全局变量
- 当 f & g 修改相同的全局变量时,表达式 f() 的值是否> g() 未定义或未指定?
- 访问全局变量以修改值
- 并发修改和读取单个全局变量
- 修改全局变量