Inter-process Communication
This page was last modified 2007-01-15 15:43:01 by Puchu.Net user Choco. (Show history)


Why use IPC?

If you want to write applications that send and receive data from each other, receive signals from other processes or terminal, or make your application multi-threaded, IPC is necessary.

Shared Memory

Code segment below shows how to initialize and release shared memory:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

/* allocate and attach */
int shm_id = shmget(<key>, <size>, IPC_CREAT | <perms>);
char *ptr = shmat(shm_id, (char *)(NULL), 0);

(now you can work with *ptr, depending on <perms>)

/* detach and destroy */
shmctl(shm_id, 0, IPC_RMID);


There are two types of semaphore: binary semaphore (similar to mutex) and counting semaphore. They are different in the range of numerical values they can store.

Binary semaphore and mutex are different:

  • semaphore is typically used to restrict simultaneous access up to a limit
  • mutex is typically used to serialize access, allow only one thread access to one section protected by mutex
  • mutex is slightly more efficient than binary semaphores
  • mutex can only be unlocked by the thread that locked it before

Here is how to access semaphore:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

int sem_id = semget(IPC_PRIVATE, <size>, <perms>);

(now you need to use semctl/semop to control
semaphore you created, attached to ID sem_id)

/* remove semaphore*/
shmctl(sem_id, 0, IPC_RMID);


Once you install a signal handler, your application can receive signals from other processes, executing the signal handler code when that happend.

#include <signals.h>

/* install handler*/
signal(<signal>, <function>);

/* send signal to a process*/
kill(<signal>, <process ID>);

/* signal self */

Monitor IPC Resources

Use command `ipcs` to show shared resources in use. If your threads are killed before they can release shared resources, you can use command `ipcrm` to reclaim memory.



Document is accessible from © 2002-2010 Sean Yang, Karen Yang, Don Yang and/or respective authors, all rights reserverd.

This material may contain (biased) opinions, inappropriate materials for numerous individuals, work of other authors from the internet, links that refer to other web documents and resources, or origial work that cannot be use for personal or commercial purposes. Please respect the work of original authors.

Creative Commons License
Powered By MediaWiki

© 2002-2010 Sean Yang, all rights reserved.