访问全局变量以修改值

Access to the global variable to modify the value

本文关键字:修改 全局变量 访问      更新时间:2023-10-16

我有一个带有全局变量(如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;
}