views:

100

answers:

5

I have to work with two C programs that communicate via a file-based interface. That is, each of them has a main loop where it polls three or four files (fopen, fscanf), reacts to what it reads and eventually makes its own changes to the files (fprintf) for the other process to read.

Now I have to condense these two programs into a single program, with minimal changes to the program logic and the code in general. However, mainly for aesthetic reasons I'm supposed to replace the file-based communication with something in-memory.

I can imagine a few hacky ways to accomplish this, but I'm sure that stackoverflow will give me a hint at a beautiful solution :)

A: 

Use a global string with sscanf and sprintf instead of a file.

Dani
Sounds reasonable, but would require me to replace/remove the fopen, fclose, etc calls. Also the checks whether a file exists. However it's certainly an OK solution, but lets see what other people come up with :)
niscy
This might also be the time to think about adding some abstraction. Instead of having the `fopen()`, `fclose()` etc. used directly, replace those with functions such as `HLINK open_link()`, `close_link( HLINK )`, `read_link_data( HLINK )` etc. where `HLINK` is a typedef for 'something', that will depend on the mechanism you decide to use. Thus, if you go through this exercise again in the future, you will only have change the type definitions and a few functions.
Praetorian
You can alwais #define fscanf sscanf etc, if you don't want to change the code.
Dani
-1 for global-variable solution.
R..
+5  A: 

Since you tagged this Linux, I'm going to suggest open_memstream. It was added to POSIX with POSIX 2008, but it's been available on glibc-based Linux systems for a long time. Basically it lets you open a FILE * that's actually a dynamically-growing buffer in memory, so you wouldn't have to change much code. This "file" is write-only, but you could simply use sscanf instead of fscanf on the buffer to read it, or use fmemopen (which doesn't have the dynamic-growth semantics but which is very convenient for reading from in-memory buffers).

R..
A: 

RabbitMQ is a really robust/elegant solution for event processing. After mucking with state machines for the past few years this has been a breath of fresh air. There are other messaging servers with C libs like OPenAMQ.

ebt
A: 

Since you tagged this Linux, I'd suggest putting the communication files on /dev/shm. That way you sort-of replace the file-based communication with an in-memory one, without actually altering any of the application logic :-)

Christoffer
A: 

You say that you have condensed the reader / Writer Processes into a single Program. So, now you have different threads for the purpose? If so, i think a mutex-guarded global buffer should serve the purpose well enough.

s_b