The purpose of my code is to execute two child processes and increment a shared variable counter. Each process should increment it by 1 million each. Here is my code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
typedef struct
{
int value;
} shared_mem;
shared_mem *counter;
//these next two processes are the ones that increment the counter
process1()
{
int i=0;
for(i=0;i<1000000;i++)
counter->value++;
}
process2()
{
int i=0;
for(i=0;i<1000000;i++)
counter->value++;
}
/* The Main Body */
main()
{
key_t key = IPC_PRIVATE; /* shared memory key */
int shmid; /* shared memory ID */
shared_mem *shmat1;
int pid1; /* process id for child1 */
int pid2; /* process id for child2 */
/* attempts to attach to an existing memory segment */
if (( shmid = shmget(key, sizeof(int), IPC_CREAT | 0666)) < 0)
{
perror("shmget");
return(1);
}
/*attempts the shared memory segment */
if((counter = (shared_mem *)shmat(shmid, NULL, 0)) == (shared_mem *) -1)
{
perror("shmat");
return(1);
}
/*initializing shared memory to 0 */
counter->value = 0;
pid1=fork();
/* fork process one here */
if(pid1==0)
{
printf("I am child 1 with PID %d\n", getpid());
process1();
}
else
{
pid2=fork();
if(pid2==0)
{
printf("I am child 2 with PID %d\n", getpid());
process2();
}
else
{
wait(NULL);
printf("I am parent with PID %d\n", getpid());
printf("Total counter value is: %d\n", counter->value);
}
}
/*deallocate shared memory */
if(shmctl(shmid, IPC_RMID, (struct shmid_ds *)0)== -1)
{
perror("shmctl");
return(-1);
}
return(0);
}
The counter output is hovering around 1 million, but shouldn't it hover around 2 million? I think I am not understanding something about the way the processes increment. Thanks a lot in advance, and I apologize if the code is too long but I am not sure what I could have included and what I could have excluded.