Master Linux Inter‑Process Communication: Pipes, Signals, Shared Memory & More
This guide explains the core Linux inter‑process communication mechanisms—including pipes, signals, files, semaphores, shared memory, message queues, sockets, and Unix‑domain sockets—detailing their concepts, typical use‑cases, and providing concise C code examples for each.
Introduction
In Linux a process is an executing instance of a program. Inter‑Process Communication (IPC) mechanisms allow processes to exchange data and synchronize their actions.
Pipes
Pipes provide a unidirectional byte stream. Anonymous pipes work only between related processes (e.g., parent‑child) and are created with pipe(). Named pipes (FIFOs) are special files that can be opened by unrelated processes.
#include <unistd.h>
int main() {
int pipefd[2];
pipe(pipefd); // create anonymous pipe
if (fork() == 0) { // child
close(pipefd[1]); // close write end
char buf[5];
read(pipefd[0], buf, 5);
} else { // parent
close(pipefd[0]); // close read end
write(pipefd[1], "hello", 5);
}
return 0;
}Named pipe example (FIFO):
#include <sys/stat.h>
#include <fcntl.h>
int main() {
const char *path = "/tmp/my_fifo";
mkfifo(path, 0666); // create FIFO
// server reads
int fd = open(path, O_RDONLY);
char buf[1024];
read(fd, buf, sizeof(buf));
close(fd);
// client writes
fd = open(path, O_WRONLY);
write(fd, "message", 8);
close(fd);
return 0;
}Signals
Signals are asynchronous notifications (e.g., SIGINT, SIGTERM). Handlers are installed with signal() or sigaction().
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void handler(int sig) {
printf("Received signal: %d
", sig);
}
int main() {
signal(SIGINT, handler); // handle Ctrl+C
while (1) sleep(1);
return 0;
}Files as IPC
Regular files can be used for simple data exchange. When multiple writers are involved, file locks via fcntl or flock prevent race conditions.
#include <fcntl.h>
#include <unistd.h>
int main() {
const char *file = "/tmp/ipc_file";
int fd = open(file, O_RDWR|O_CREAT, 0666);
write(fd, "Hello from A", 12);
close(fd);
// reader
fd = open(file, O_RDONLY);
char buf[20];
read(fd, buf, 12);
close(fd);
return 0;
}Note: Use file locks or other synchronization primitives when several processes write to the same file concurrently.
Semaphores
POSIX named semaphores ( sem_open, sem_wait, sem_post) are preferred for synchronizing access to shared resources.
#include <semaphore.h>
#include <unistd.h>
int main() {
sem_t *sem = sem_open("/log_semaphore", O_CREAT, 0644, 1);
sem_wait(sem);
// critical section
sem_post(sem);
sem_close(sem);
return 0;
}Shared Memory
Shared memory provides the fastest IPC because data resides in RAM and is accessed without kernel copying. It can be created anonymously with mmap(MAP_ANONYMOUS), as a file‑backed mapping, via POSIX shm_open, or using System V APIs.
#include <sys/mman.h>
int main() {
size_t size = 4096;
void *addr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
// use *addr as shared data
munmap(addr, size);
return 0;
}POSIX named shared memory example:
#include <sys/mman.h>
#include <fcntl.h>
int main() {
const char *name = "/example_shm";
int fd = shm_open(name, O_CREAT|O_RDWR, 0666);
ftruncate(fd, 4096);
void *ptr = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
// read/write via ptr
munmap(ptr, 4096);
close(fd);
shm_unlink(name);
return 0;
}System V shared memory example:
#include <sys/shm.h>
int main() {
key_t key = ftok("/tmp", 'A');
int shmid = shmget(key, 1024, IPC_CREAT|0666);
char *addr = shmat(shmid, NULL, 0);
// use addr
shmdt(addr);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}Message Queues
System V message queues ( msgget, msgsnd, msgrcv) allow asynchronous sending and receiving of fixed‑size messages.
#include <sys/msg.h>
struct message { long mtype; char mtext[100]; };
int main() {
key_t key = ftok("queuefile", 65);
int msqid = msgget(key, 0666|IPC_CREAT);
struct message msg = {1, "Hello World"};
msgsnd(msqid, &msg, sizeof(msg.mtext), 0);
msgrcv(msqid, &msg, sizeof(msg.mtext), 1, 0);
printf("Received: %s
", msg.mtext);
msgctl(msqid, IPC_RMID, NULL);
return 0;
}Sockets (TCP/UDP)
Sockets provide network‑level IPC and can also be used locally. A minimal TCP server creates a listening socket, accepts a connection, reads data, and closes the sockets.
#include <sys/socket.h>
#include <netinet/in.h>
int main() {
int server = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = { .sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY, .sin_port = htons(8080) };
bind(server, (struct sockaddr*)&addr, sizeof(addr));
listen(server, 3);
int client = accept(server, NULL, NULL);
char buf[1024];
read(client, buf, sizeof(buf));
printf("Message: %s
", buf);
close(client);
close(server);
return 0;
}Unix Domain Sockets
Unix‑domain sockets enable high‑performance local IPC without involving the network stack. They support stream and datagram modes.
#include <sys/un.h>
int main() {
int srv = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un addr = { .sun_family = AF_UNIX };
strcpy(addr.sun_path, "/tmp/unix_socket");
bind(srv, (struct sockaddr*)&addr, sizeof(addr));
listen(srv, 5);
int cli = accept(srv, NULL, NULL);
char buf[100];
read(cli, buf, sizeof(buf));
printf("Received: %s
", buf);
close(cli);
close(srv);
unlink("/tmp/unix_socket");
return 0;
}Choosing the Right IPC Mechanism
Use anonymous pipes for simple parent‑child streams, named pipes (FIFOs) when unrelated processes need a file‑based channel, signals for asynchronous notifications, shared memory (combined with semaphores or file locks) for high‑throughput data exchange, message queues for ordered asynchronous messaging, and sockets (or Unix‑domain sockets) when bidirectional communication or network transparency is required.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
