How to share state between programs?

366 views Asked by At

I have 2 programs that must communicate with each other. They should share state (variables, files - i don't know how to achieve this). One program should read it and react on changes - the other should write to this global state.

Using files for this purpose is not even slow, it is difficult to read a file that someone writes at the same time.

What is the best way to achieve this shared state between programs? (looking for a cross-platform solution)

2

There are 2 answers

2
Ramzendo On

One idea to achieve this is to export your data (variables, state, etc) in a json file and store it in a temporary file. Once you have done this, with your second program you can read that json file that has been generated by the first program and parse it so you can assign those variables to your second program.

If you are working with those programs in a network, then I would suggest to use REST.

XML and Json are formats to exchange information across platforms. You will have to make sure you have a Json parser in both programs.

I hope that helps.

2
Juan Tomas On

The normal way to keep two processes synchronized in state is to use IPC (InterProcess Communication). But IPC may not work here, if by "cross-platform" you mean e.g. having a python app on Linux stay synced with a native Windows app on Windows. In that case, you're pretty much stuck with REST using HTTP to serve up Json, XML, etc.

Writing the state to a network-accessible temp file will create all kinds of problems. Better is to have one process act as a "server", serving state to "client" processes. When a client wants to update its state, it requests the latest state from the server at that time. The server responds with a Json or equivalent object that contains the latest state. The transaction is discrete. There's no chance of trying to read a file while another process is writing it, or reading a file that's out of date.