Issue
I'm working on a C application that involves multiple processes, both child processes and the parent process, and I'm trying to share statistics between them using shared memory and semaphores. However, I'm encountering an issue with my code where the child process doesn't seem to correctly modify the shared statistics in the parent process, which is preventing me from printing them accurately.
In main, I created and attached shared memory:
stats_shm_id = create_shared_memory(SHM_STATS_KEY, sizeof(Statistics));
stats = (Statistics *)attach_shared_memory(stats_shm_id);
The init function does:
stats = (Statistics *)malloc(sizeof(Statistics));
stats->shared_data_1 = 0;
stats->shared_data_2 = 0;
The print function does:
printf("%d",stats->shared_data1);
printf("%d",stats->shared_data2);
My goal is to have the child process modify the shared statistics in the parent process so that they can be printed accurately. However, it seems that the changes made by the child process aren't reflected in the parent process when I call the print_statistics() function. I've verified that semaphores are being used correctly to synchronize access to the statistics.
Could someone kindly help me understand what might be going wrong? Could this be a synchronization issue? What steps should I consider to troubleshoot and resolve this problem?
Thank you in advance for any help and suggestions!
Solution
Could someone kindly help me understand what might be going wrong?
Your initialize_statistics()
function sets the global stats
variable to point to (unshared) dynamically allocated memory. This foils the previous work to set up and attach to a shared memory segment. The processes are not, in fact, using shared memory at all.
Answered By - John Bollinger Answer Checked By - Pedro (WPSolving Volunteer)