I'm trying to share an instance of a class between two programs. This is a glorified producers consumers problem; however, for abstraction purposes, I have put a mutex in the class.
I've seen instances of sharing structs between processes, but this generally involved a fork. I want to keep the processes separate, because they will be doing two different things so half of the program\code segment will be wasted on each process.
It might be easier to show than try to explain.
class my_class
{
private:
sem_t mutex;
data_type *my_data; //just some linked list
fstream some_file;
public:
my_class();
data_type* retrieve();
void add(string add);
};
my_class::my_class()
{
my_data = new data_type();
sem_init(&mutex, 0, 1);
my_file.open("log", ios::out);
}
data_type* my_class::retrieve()
{
data_type *temp = NULL;
sem_wait(&mutex);
if(my_data -> next != NULL)
{
temp = my_data;
my_data = my_data -> next;
}
sem_post(&mutex);
return my_data;
}
void my_class::add(string data)
{
data_type *temp = new data_type();
temp -> data = data;
data_type *top;
sem_wait(&mutex);
top = my_data;
while(top -> next -> next) //adds it to the end. The end's next is set to NULL
{
top = top -> next;
}
top -> next = temp;
my_file << name << "\n";
sem_post(&mutex);
}
What I'm really looking for is a way to share an instance of this class as a pointer. This way, I can then have threads that can access this instance. I think because of how much sharing I want to do, it needs to go on the heap and not the stack.
I wouldn't consider making this its own program and then using networking i\o to interact because of how simple it is. Needless to say, this is not exactly what I'm doing; however I think I've made a simplified\generic enough example that if this can be solved then I can easily apply it to my solution and it might help others.
Again, I'm looking for a way to share one instance of this code between two separate processes.
I don't know if this can be done because the class has a linked list in it let alone a file in it. If it can, then whose heap and file table does it fill (both?).
EDIT:
Thanks for the help so far; however, it should be worth pointing out that both processes may not be running at the same time. One acts as a daemon and the other will appears intermittently. Both programs already have threads, so that's why I want to do it on the heap.