I’m writing an HTTP server for a homework assignment, and I’m trying to make sure I’m using shared memory correctly. Here’s a summary of the relevant stuff:
struct my_struct{
int num_kids;
...
}
int main(arg stuff){
...
struct mystruct *shared_data;
// shmget & shmat here
shared_data = (struct mystruct *) shared_memory;
...
while(mainloop){
...
if(incoming_connection)
if(!fork())
childstuff(shared_data);
}
...
while(shared_data->num_kids > 0)
sleep(1);
// shmdt & shmctl here
}
void childstuff(struct mystruct *shared){
shared->num_kids++;
...
shared->num_kids--;
exit(0);
}
Questions
1) Will childstuff() be able to properly access the shared memory?
2) Do I need to call shmdt() in the child?
3) Will calling exit() rather than _exit() in the child mess up the shared memory? I know exit() cleans up some stuff that _exit() doesn’t before calling _exit(), but I’m not sure what extra stuff exit() cleans up (other than flushing I/O buffers).
My understanding is that in modern operating systems calling
exitcauses the process to end and memory allocated to the thread pool will be de-allocated. However, that is a really sloppy way to cleanup memory usage and really shouldn’t be counted upon because there are a lot of things that can interrupt and kill the process, not to mention the obvious potential problem of running out of memory.This is where OOP can come in really handy, but I assume that since this is a homework assignment you’re stuck writing it in C?
I would write a new module that implements a list of some type (e.g. a linked list) to manage the allocation and de-allocation of shared memory. The module would need some exposed APIs for allocating memory and freeing memory. (Think: wrapper functions for
mallocandfree.) It would also need a lock mechanism to enforce singular access, so that the two processes don’t stop on each other.