Shared memory is the fastest form of IPC. Once the memory is mapped into the address space of processes that are sharing the memory region, no kernel action is needed. However, it needs synchronization between the sharing processes.
Below example shows client-server using shared memory. Noted that shared memory appears both at address space of client and server.
Take a example about the case that the parent process and child process can not shared a global variable 'count'.
int count = 0; int main(int argc, char **argv) { int i,nloop=300,zero=0,*ptr; sem_t *mutex; // assign value of 1 to semaphore //if ((mutex = sem_open("semap", O_CREAT | O_EXCL, 0644, 1)) == SEM_FAILED) { if ((mutex = sem_open("semap", O_CREAT, 0644, 1)) == SEM_FAILED) { perror("semaphore initilization"); exit(0); } sem_unlink("semap"); if (fork() == 0) { for (i =0; i < nloop; i++) { sem_wait(mutex); printf("child:%d\n", count++); sleep(2); sem_post(mutex); sleep(2); } } /* back to parent process */ for (i = 0; i < nloop; i++) { sem_wait(mutex); printf("parent: %d\n", count++); sem_post(mutex); sleep(1); } exit(0); }
The output is below.
In above code, to synchronize access the count variable, we use a named mutex. This mutex is truly shared by parent and child. However, 'count' is not shared memory. Both parent and child has their own memory space of 'count'. That is reason parent and child increase 'count' independently.
Next, we will check how to use shared memory for 'count' global variable.
Please update your presentation about memory mapping, mapped file ASAP!!!
ReplyDelete