I'm sharing a counter variable between a multi-process program, where processes are created using the fork() call. I'm using the following code to create a shared memory where the counter is stored, and can be accessed and incremented by each process.
This is the thread creation mechanism in the main parent thread
void createSHM()
{
int key = SHMKEY;
int *shm;
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit(1);
}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
*shm=0
}
and this is the function called in each of the forked processes to get the value of the counter, and increment it.
int attachSHMandIncrement()
{
int key = SHMKEY;
int *shm;
if ((shmid = shmget(key, SHMSZ, 0666)) < 0) {
perror("shmget");
exit(1);
}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
*shm++;
return *shm;
}
I'm not sure if this implementation is race free? Can anyone comment on if it is, and if not, an example of how this can be made race free?
Given the fact that these are forked processes and will inherit the memory at the time of fork. Is there anything I should keep in mind? I've done this before in totally separate processes but here I might have to do it in forked processes.