**Modify global variable from external process**

Hi, I'd like to be able to modify a global variable of a main program from an external process. Does anyone know any idea of how I can do it ??
Not safely, no.

Unless your programs know how to communicate with each other.
Ok, but is there any way I can make the two programs communicate with each other ??
Look up interprocess communication, particularly shared memory.
Boost.Interprocess will help you with this.
ok, thanks for the info !

you could also export the variable to the system env, or export to a tmp file, of if in windows, you could use the registry, though using registry could potentially be dangerous...

Personally, I would export to the system env.,.. There is a function to do so in C++ i do beleive... Dunno how standard it is though. You'll have to look it up.

Those are the Easy ways ^
Last edited on
Using boost isn't hard either and it works on many different platforms.

Example process 1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
using namespace boost::interprocess;

int main()
{
  shared_memory_object shm(open_or_create,"yourSHMName",read_write);
  offset_t currentSize;
  if (!shm.get_size(currentSize))return 1;
  if (currentSize<sizeof(int))shm.truncate(sizeof(int));
  mapped_region region(shm,read_write,0,sizeof(int));
  
  int* sharedInt=static_cast<int*>(region.get_address());
  *sharedInt=50;
}


Example process 2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
using namespace std;
using namespace boost::interprocess;

int main()
{
  shared_memory_object shm(open_only,"yourSHMName",read_write);
  offset_t currentSize;
  if (!shm.get_size(currentSize))return 1;
  if (currentSize<sizeof(int))shm.truncate(sizeof(int));
  mapped_region region(shm,read_write,0,sizeof(int));

  int* sharedInt=static_cast<int*>(region.get_address());
  cout << *sharedInt << endl;
}


If you no longer need the shared memory, you need to explicitly delete it, as it will persist even when both processes have terminated:

shared_memory_object::remove("yourSHMName");


Of course, you can have more than just one shared int, this works for structures and arrays as well, as long as they're trivially copyable.
If you want to use standard containers or other classes that support custom memory allocators, you can use boost's managed shared memory.
Last edited on
Topic archived. No new replies allowed.