C
Summary - IPC
Combine pipe, shared memory and semaphore to write an IPC app.
IPC summary
You learned five IPC tools: pipe for one-way flow between related processes, FIFO for named channels between any two processes, shared memory for the fastest common memory, message queue for typed messages, semaphore for synchronization.
Most real applications combine them: shared memory shares data, semaphore orders access; pipe or FIFO carries small notifications. In this summary we will increment a counter with shared memory and semaphore, and return the result over a pipe.
Exercise Combine IPC
Set up a channel with int fds[2]; pipe(fds);. Set up segment and semaphore with int shmid = shmget(IPC_PRIVATE, 64, 0600 | IPC_CREAT); and int semid = semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT);. Set int *shared = (int *)shmat(shmid, NULL, 0); *shared = 0; and semctl(semid, 0, SETVAL, 0);. Fork a child with pid_t pid = fork();. In the child: close(fds[0]); struct sembuf op = {0, -1, 0}; semop(semid, &op, 1); int v = *shared; write(fds[1], &v, sizeof(int)); close(fds[1]); _exit(0);. In the parent: close(fds[1]); *shared = 7; struct sembuf op = {0, 1, 0}; semop(semid, &op, 1); int got = 0; read(fds[0], &got, sizeof(int)); printf("ipc: %d\n", got);. Cleanup: close(fds[0]); wait(NULL); shmdt(shared); shmctl(shmid, IPC_RMID, NULL); semctl(semid, 0, IPC_RMID);.
Show example solution
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
int fds[2];
pipe(fds);
int shmid = shmget(IPC_PRIVATE, 64, 0600 | IPC_CREAT);
int semid = semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT);
int *shared = (int *)shmat(shmid, NULL, 0);
*shared = 0;
semctl(semid, 0, SETVAL, 0);
pid_t pid = fork();
if (pid == 0) {
close(fds[0]);
struct sembuf op = {0, -1, 0};
semop(semid, &op, 1);
int v = *shared;
write(fds[1], &v, sizeof(int));
close(fds[1]);
_exit(0);
}
close(fds[1]);
*shared = 7;
struct sembuf op = {0, 1, 0};
semop(semid, &op, 1);
int got = 0;
read(fds[0], &got, sizeof(int));
printf("ipc: %d\n", got);
close(fds[0]);
wait(NULL);
shmdt(shared);
shmctl(shmid, IPC_RMID, NULL);
semctl(semid, 0, IPC_RMID);
return 0;
}
Next steps
You completed the IPC toolset. These foundations are the core of database servers, message queue systems and microservice communication. On the same machine, shared memory and semaphore are common; for networks, sockets are used.
Next topics: file locking for data integrity, terminal I/O for interactive apps, dynamic loading for plugin systems and cryptography for security. All can be built on top of IPC.
Test yourself
-
Which IPC tool is designed for synchronization?
- pipe
- FIFO
- message queue
- semaphore
Show answer
semaphore — The semaphore is designed for synchronization.
-
Match IPC tools
- pipe
- Related one-way
- FIFO
- Named channel
- shm
- Shared memory
- semaphore
- Synchronization
Next lesson: flock