SyntaxPilot
Courses/CS Fundamentals for Placements/Lesson 19

CS Fundamentals for Placements · Lesson 19 of 90 · 17 min

Inter-process communication

independent vs cooperating processesshared memorymessage passingdirect vs indirect communicationmailboxsynchronous vs asynchronous messaginganonymous pipesnamed pipes (FIFO)message queuessignals (SIGINT, SIGTERM, SIGKILL, SIGCHLD)signal handlerssockets as IPCremote procedure call (RPC)

These are the notes for CS Fundamentals for Placements, episode 19. In episode 18 you created processes with fork, and every child got its own copy of memory. Today's question: if every process lives in its own memory, how do two processes talk? You will meet independent vs cooperating processes, the two families of inter-process communication (IPC) (message passing and shared memory), anonymous pipes, named pipes (FIFOs), message queues, direct vs indirect communication, mailboxes, synchronous vs asynchronous messaging, signals (SIGINT, SIGTERM, SIGKILL, SIGCHLD) and signal handlers, sockets as IPC, and remote procedure call (RPC). Every term is explained in plain words the first time it appears, and there is a full glossary at the end.

All outputs below are real: the C programs were compiled with gcc -O2 (gcc 13.3, glibc 2.39) and run on Linux x86-64 on 30 October 2026, with standard output going to a pipe, exactly as in the SyntaxPilot compiler. Signal numbers are the Linux x86-64 ones.

A quick refresher: a process is a running program with its own memory and a PID. fork() creates a child that is a copy of its parent. The kernel is the core of the operating system; a system call asks it to do something.

The seven problems

Problem What it teaches
Two processes must talk Independent vs cooperating processes, IPC, why a global variable fails, message passing vs shared memory
Send data one way Anonymous pipes, file descriptors, read/write ends, byte streams, end of file
Strangers must talk Named pipes (FIFOs)
Keep messages separate Message queues; direct vs indirect communication, mailboxes; synchronous vs asynchronous
Share lots of data fast Shared memory with mmap; why it needs synchronization
Say "stop now!" Signals, default actions, signal handlers, kill, SIGINT, SIGTERM, SIGKILL, SIGCHLD
Talk both ways, across machines Sockets, client and server, RPC, stubs, marshalling

Problem 1: two processes must talk

Real-life example: the restaurant with two rooms. The counter (one process) takes orders. The kitchen (another process) cooks, in a different room. A wall stands between them: neither can read the other's notebook. That wall is memory isolation: the OS keeps every process's memory private so one buggy program can't scribble on another. But the counter and the kitchen must still talk: "5 chai, please", "order ready".

Inter-process communication (IPC) is any mechanism that lets processes exchange data or notify each other.

Independent vs cooperating processes

Independent process Cooperating process
Meaning Shares no data with any other process; nothing it does affects others Can affect, or be affected by, other processes
Example A calculator and a music player A browser's tab processes reporting to the main browser process; ls \| wc -l in a shell
Needs IPC? No Yes

Why let processes cooperate? Information sharing (several processes need the same data), speed (split a job so parts run in parallel), and modularity (build a system from small programs, like a shell pipeline).

The obvious attempt: a global variable (fails)

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int orders = 0;                     // a global variable

int main() {
    pid_t id = fork();
    if (id == 0) {                  // child: the kitchen
        orders = 5;
        printf("child:  orders = %d\n", orders);
        return 0;
    }
    wait(NULL);                     // parent: the counter
    printf("parent: orders = %d\n", orders);
    return 0;
}

Output:

child:  orders = 5
parent: orders = 0

Why it failed: fork gave the child its own copy of every variable. The child changed its copy; the parent's copy never changed. The processes need the kernel's help to cross the wall.

The two families of IPC

Message passing Shared memory
Idea Processes send each other messages; the kernel carries them The kernel maps one region of memory into both processes
Real-life picture Passing notes through a hatch in the wall A whiteboard on the wall that both rooms can see
Kernel involved On every send and receive (a system call each time) Only to set the region up
Speed Slower: every byte is copied into the kernel and out again Fastest: plain memory reads and writes
Safety Simple: the kernel keeps order You must stop processes from writing at the same time
Examples Pipes, FIFOs, message queues, sockets mmap(MAP_SHARED), shm_open, shmget

Problem 2: send data one way (anonymous pipes)

Real-life example: an order tube in the wall. The kitchen drops notes in at one end, they slide down, and the counter takes them out at the other end.

In the restaurant In the OS
A tube through the wall A pipe: a one-way channel kept inside the kernel
Kitchen end: only puts notes in The write end, fd[1]: write() puts bytes in
Counter end: takes notes out, waits if empty The read end, fd[0]: read() takes bytes out, blocks (waits) if the pipe is empty

A file descriptor is a small integer the kernel gives your process to refer to an open file, pipe, socket or device. Every process starts with three: 0 = standard input, 1 = standard output, 2 = standard error. Memory trick: fd[0] is for reading like stdin (0), fd[1] is for writing like stdout (1).

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    int fd[2];
    pipe(fd);                       // fd[0] = read end, fd[1] = write end
    if (fork() == 0) {              // child: the kitchen writes
        close(fd[0]);
        char *msg = "5 chai ready";
        write(fd[1], msg, strlen(msg) + 1);
        return 0;
    }
    close(fd[1]);                   // parent: the counter reads
    char buf[64];
    read(fd[0], buf, sizeof buf);   // waits until data arrives
    printf("parent got: %s\n", buf);
    wait(NULL);
    return 0;
}

Output:

parent got: 5 chai ready

How it works: pipe(fd) creates the pipe and fills fd with its two ends. fork() copies the parent's open file descriptors into the child, so both processes hold both ends. Each process closes the end it doesn't use. (strlen(msg) + 1 also sends the terminating '\0' so the reader can print it as a string.)

A pipe created by pipe() has no name, so it is called an anonymous pipe (or unnamed pipe). Your shell builds one every time you type | between two commands (see the mini project).

A pipe is a byte stream (fails as messages)

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    int fd[2];
    pipe(fd);
    if (fork() == 0) {
        write(fd[1], "chai", 4);    // message 1
        write(fd[1], "samosa", 6);  // message 2
        return 0;
    }
    wait(NULL);                     // both writes are done now
    char buf[64] = {0};
    int n = read(fd[0], buf, sizeof buf - 1);
    printf("one read got %d bytes: %s\n", n, buf);
    return 0;
}

Output:

one read got 10 bytes: chaisamosa

Two writes came out as one read. A pipe is a byte stream: a continuous flow of bytes with no message boundaries, like water in a pipe. If you need separate messages, mark where each ends (for example with a newline, see practice 2) or use a message queue.

The rules of an anonymous pipe

  • One-way (half-duplex in use): data flows from the write end to the read end. A two-way conversation needs two pipes.
  • Byte stream: no message boundaries.
  • FIFO order: bytes come out in the order they went in.
  • Limited kernel buffer: the kernel holds the bytes in a buffer of limited size (on Linux the default pipe capacity is 64 KiB per pipe(7)). read blocks when it is empty; write blocks when it is full.
  • End of file (EOF): when every write end is closed, read returns 0, meaning "no more data will ever come". If any process (even the reader itself) still holds a write end open, a reader waiting for EOF waits forever.
  • No name: the ends can only be inherited through fork, so only related processes (a parent and its descendants) can use it.

Problem 3: strangers must talk (named pipes, FIFO)

Fix: give the pipe a name in the file system. A named pipe, also called a FIFO (first in, first out), is a special file created with mkfifo. Any process with permission can open it by name, one for writing and one for reading, exactly like a file.

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>

int main() {
    mkfifo("orders.fifo", 0666);    // a pipe with a NAME on disk
    if (fork() == 0) {              // writer: any process could open it
        int w = open("orders.fifo", O_WRONLY);
        write(w, "table 4: 2 samosa", 18);
        close(w);
        return 0;
    }
    int r = open("orders.fifo", O_RDONLY);
    char buf[32];
    read(r, buf, sizeof buf);
    printf("reader got: %s\n", buf);
    close(r);
    wait(NULL);
    unlink("orders.fifo");          // remove the name
    return 0;
}

Output:

reader got: table 4: 2 samosa

Here the writer happens to be our child, but it could be any unrelated program that opens orders.fifo. 0666 is the permission (read and write for everyone, reduced by your umask). O_WRONLY / O_RDONLY open for writing only / reading only. Opening a FIFO blocks until the other side opens it too. unlink removes the name, like deleting a file.

From a terminal: mkfifo orders.fifo creates one, and ls -l shows it with a p (pipe) at the start of its permissions. Try cat orders.fifo in one terminal and echo hi > orders.fifo in another.

Anonymous pipe Named pipe (FIFO)
Created with pipe(fd) mkfifo("name", mode)
Has a name? No Yes, a path in the file system
Who can use it Related processes (via fork) Any processes with permission
Lifetime Until all ends are closed The name stays until unlink/rm
Data stored on disk? No No: only the name is on disk; the bytes pass through the kernel
Direction / format One-way byte stream One-way byte stream

Problem 4: keep messages separate (message queues)

Fix: let the kernel keep whole messages. A message queue is a list of messages kept by the kernel; each message is delivered whole (never glued to another) and carries a type number, so a receiver can ask for only the type it wants.

#include <stdio.h>
#include <sys/msg.h>
#include <unistd.h>
#include <sys/wait.h>

struct order { long type; char text[32]; };

int main() {
    int q = msgget(IPC_PRIVATE, 0600);          // create a queue
    if (fork() == 0) {
        struct order a = {1, "chai"}, b = {2, "samosa"}, c = {1, "coffee"};
        msgsnd(q, &a, sizeof a.text, 0);        // type 1 = drinks
        msgsnd(q, &b, sizeof b.text, 0);        // type 2 = snacks
        msgsnd(q, &c, sizeof c.text, 0);
        return 0;
    }
    wait(NULL);
    struct order m;
    while (msgrcv(q, &m, sizeof m.text, 1, IPC_NOWAIT) > 0)
        printf("drinks counter got: %s\n", m.text);
    msgrcv(q, &m, sizeof m.text, 2, 0);
    printf("snacks counter got: %s\n", m.text);
    msgctl(q, IPC_RMID, NULL);                  // delete the queue
    return 0;
}

Output:

drinks counter got: chai
drinks counter got: coffee
snacks counter got: samosa
Call What it does
msgget(IPC_PRIVATE, 0600) Create a new System V message queue (permissions 0600 = owner read/write); returns its id. Unrelated processes use a shared key (from ftok) instead of IPC_PRIVATE.
msgsnd(q, &msg, size, 0) Send a message. The struct must start with a long type greater than 0; size counts only the data after it.
msgrcv(q, &msg, size, type, flags) Receive the oldest message of that type (0 = any type). Flag 0 = wait if none; IPC_NOWAIT = return -1 at once if none.
msgctl(q, IPC_RMID, NULL) Delete the queue. A queue lives in the kernel until deleted, even after every process exits (ipcs -q lists them).

POSIX also has message queues (mq_open, mq_send, mq_receive) with priorities instead of types. POSIX is a common standard for UNIX-like operating systems; System V is the older UNIX API family that msgget, shmget and semget come from.

Design choices in message passing

Real-life example: a phone call vs a post box.

In real life In IPC Meaning
A phone call to one exact person Direct communication Sender and receiver name each other: send(P, msg), receive(Q, msg). A link joins exactly those two.
The post box at your society gate Indirect communication through a mailbox (also called a port) Messages are sent to and received from a shared mailbox: send(box, msg). Processes only need to know the mailbox, and many can share it. A message queue is a mailbox.
Standing at the counter until your order is ready Synchronous (blocking) send waits until the message is delivered/accepted; receive waits until a message arrives. msgrcv(..., 0) blocks.
Dropping a letter and walking away Asynchronous (non-blocking) The call returns at once: send just queues the message; receive returns a message or "nothing yet". msgrcv(..., IPC_NOWAIT) returns -1 if the queue is empty.

When both send and receive block, it is called a rendezvous. Message buffering in a link can have zero capacity (sender must wait for the receiver), bounded capacity (sender waits only when the queue is full), or unbounded capacity (sender never waits).

Problem 5: share lots of data fast (shared memory)

Every message so far was copied twice: from the sender into a kernel buffer, then from the kernel into the receiver, with a system call each time. For short orders that's fine; for big data (a video app passing 4K frames 60 times a second from a decoder process to a display process) the copying wastes time.

Fix: ask the kernel to map one region of memory into both processes.

#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    int *orders = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE,
                       MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    *orders = 0;                    // this memory is SHARED
    if (fork() == 0) {
        *orders = 5;                // child writes into it
        printf("child:  orders = %d\n", *orders);
        return 0;
    }
    wait(NULL);
    printf("parent: orders = %d\n", *orders);
    munmap(orders, sizeof(int));
    return 0;
}

Output:

child:  orders = 5
parent: orders = 5

The same test that failed at the start now works. mmap maps memory into the process: PROT_READ | PROT_WRITE = readable and writable; MAP_SHARED = changes are seen by every process sharing this mapping (even after fork); MAP_ANONYMOUS = not backed by a file (-1, 0 are the unused file arguments). munmap releases it.

For unrelated processes, give the region a name: shm_open("/name", ...) + ftruncate + mmap (POSIX), or shmget + shmat (System V).

The catch: the kernel no longer referees. If two processes update the same value at the same moment, one update can be lost. This is a race condition (a result that depends on the exact timing of processes or threads). Shared memory needs synchronization: tools like locks and semaphores that make processes take turns (episodes 24 to 26). You will see a race happen live in episode 20.

Problem 6: say "stop now!" (signals)

Sometimes you don't need to send data, just a quick notice: "stop now", "your child finished". Checking a pipe again and again for it would waste time.

Real-life example: the doorbell. You're reading a book. The doorbell rings: it carries no letter, just one fact, "someone's here". You stop, answer the door your own way, then go back to the same page.

Doorbell Signals
The bell rings A signal: a small numbered notice the kernel delivers to a process, interrupting whatever it was doing
You answer in your own way A signal handler: a function the process registers to run when that signal arrives
Ignore it, or do nothing special The default action if there is no handler (end the process, ignore it, stop it, or end it and dump core, depending on the signal)
Back to the same page After the handler returns, the process continues where it was interrupted
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <errno.h>

void on_signal(int sig) {           // a signal handler
    printf("caught signal %d, finishing my order first\n", sig);
}

int main() {
    setbuf(stdout, NULL);
    signal(SIGINT, on_signal);      // Ctrl+C sends SIGINT
    signal(SIGTERM, on_signal);     // a polite "please stop"
    raise(SIGINT);                  // send a signal to myself
    raise(SIGTERM);
    if (signal(SIGKILL, on_signal) == SIG_ERR)
        printf("SIGKILL handler: %s\n", strerror(errno));
    printf("still running\n");
    return 0;
}

Output:

caught signal 2, finishing my order first
caught signal 15, finishing my order first
SIGKILL handler: Invalid argument
still running

signal(sig, handler) registers a handler (production code prefers sigaction, which has clearer rules). raise(sig) sends a signal to yourself. The kernel refuses a handler for SIGKILL with EINVAL ("Invalid argument"). setbuf(stdout, NULL) turns off output buffering so the lines appear in order. (Strictly, printf is not async-signal-safe, meaning not guaranteed safe inside a handler that interrupts other code; it is fine in this tiny demo because the handler runs at a known point. In real handlers use write, or just set a flag.)

Sending signals to another process

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>

void on_child(int sig) {
    printf("parent: got SIGCHLD (%d), a child changed state\n", sig);
}

int main() {
    setbuf(stdout, NULL);
    signal(SIGCHLD, on_child);
    pid_t id = fork();
    if (id == 0) {                  // child: an endless job
        while (1) pause();
    }
    sleep(1);
    kill(id, SIGKILL);              // force it to stop, now
    int status;
    waitpid(id, &status, 0);
    if (WIFSIGNALED(status))
        printf("child killed by signal %d\n", WTERMSIG(status));
    return 0;
}

Output:

parent: got SIGCHLD (17), a child changed state
child killed by signal 9

pause() sleeps until a signal arrives. kill(pid, sig) sends any signal to a process (despite its name). WIFSIGNALED(status) is true if the child was ended by a signal, and WTERMSIG(status) gives that signal's number. From a terminal: kill PID sends SIGTERM, kill -9 PID sends SIGKILL, kill -l lists signal names.

Four signals every interview asks about

Signal Number (Linux x86-64) Sent when Default action Can be caught?
SIGINT 2 You press Ctrl+C in a terminal End the process Yes
SIGTERM 15 A polite request to stop; kill's default End the process Yes: save work, clean up, exit
SIGKILL 9 Forced stop (kill -9) End the process immediately No: can't be caught, blocked or ignored
SIGCHLD 17 A child stopped or ended Ignored Yes: a good place to call waitpid and avoid zombies

Rule of thumb: send SIGTERM first, and SIGKILL only if the program doesn't stop, because SIGKILL gives it no chance to clean up (flush files, remove temp files, close connections). SIGSTOP is the other signal that can't be caught.

Problem 7: talk both ways, across machines (sockets and RPC)

Pipes are one-way, and everything so far works only between processes on the same machine.

A socket is an endpoint for two-way communication, like one end of a phone line. Data written into one end comes out of the other, in both directions.

Socket type Address Used for
Unix domain socket (AF_UNIX) A file path, e.g. /run/app.sock Processes on the same machine
Network socket (AF_INET, AF_INET6) An IP address (finds the machine) + a port number (finds the program on it) Processes on any machines (the networks part of this course covers TCP/IP)
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/wait.h>

int main() {
    int sv[2];
    socketpair(AF_UNIX, SOCK_STREAM, 0, sv);   // two connected sockets
    if (fork() == 0) {                         // child = server
        char req[32];
        read(sv[1], req, sizeof req);
        printf("server got: %s\n", req);
        write(sv[1], "bill = 40", 10);         // reply on the SAME socket
        return 0;
    }
    write(sv[0], "price of 2 chai?", 17);      // parent = client
    char reply[32];
    read(sv[0], reply, sizeof reply);
    printf("client got: %s\n", reply);
    wait(NULL);
    return 0;
}

Output:

server got: price of 2 chai?
client got: bill = 40

socketpair creates two Unix domain sockets already connected to each other. SOCK_STREAM means a reliable byte stream (like TCP). A server is a process that waits for requests and answers them; a client sends requests. For unrelated processes or other machines, the server calls socket, bind (attach an address), listen and accept; the client calls socket and connect.

Remote procedure call (RPC)

Sockets move bytes, but programmers think in function calls. RPC lets a program call a function that runs in another process, even on another machine, as if it were a local call.

  1. The client calls price = getPrice(2); like a normal function.
  2. A client stub (small generated code standing in for the remote function) packs the function name and arguments into bytes. Packing data into a format for sending is marshalling (also called serialization).
  3. The bytes travel over a socket. The server stub unpacks them (unmarshalling) and calls the real getPrice.
  4. The result travels back the same way, and the caller just gets 40.

The difference from a local call: a network call can be slow, lost or fail halfway, so real RPC systems add timeouts (give up after a time limit) and retries. Systems differ in what happens on a retry: the call may run at most once, at least once, or (ideally) exactly once.

The whole chain

Step Fix Its limit (the next problem)
Global variable (fails: separate memory after fork) Need the kernel's help
Anonymous pipe One-way byte channel between relatives No message boundaries; no name
Named pipe (FIFO) A pipe with a file-system name: any processes Still a one-way byte stream
Message queue Whole, typed messages in a kernel mailbox Every byte copied through the kernel
Shared memory One region mapped into both: fastest Needs synchronization
Signals A numbered notice, no data Carries no data
Sockets / RPC Two-way, even across machines Network failures, timeouts

Which IPC method, when?

Method Direction Data Who can use it Speed Typical use
Anonymous pipe One-way Byte stream Related processes Medium Shell pipelines a \| b
Named pipe (FIFO) One-way Byte stream Any (same machine) Medium Simple producer → consumer between programs
Message queue One-way per message Whole typed messages Any (same machine) Medium Job queues, typed requests
Shared memory Both Anything Any (same machine) Fastest Big data: video frames, databases' buffer pools
Signal To a process Just a number Same user (or root) Fast Stop, reload config, child ended
Socket Two-way Byte stream or datagrams Any, even other machines Medium (network: slower) Client-server apps, the web
RPC Request/response Function calls Any, even other machines Like sockets Microservices calling each other

Common mistakes (and the real output)

Mistake Real output Why Fix
Expecting a global variable to be shared after fork() parent: orders = 0 Each process has its own copy Shared memory or a message
Two write() calls, one read() on a pipe, treated as two messages one read got 10 bytes: chaisamosa A pipe is a byte stream Mark message ends (newline) or use a message queue
A reader loops until read() returns 0 but never closed its own fd[1] the program hangs forever EOF only comes when every write end is closed Close every end you don't use, right after fork
signal(SIGKILL, handler) SIGKILL handler: Invalid argument SIGKILL can't be caught Handle SIGTERM for clean shutdown
Forgetting msgctl(q, IPC_RMID, NULL) the queue still shows in ipcs -q after the program ends System V queues live until deleted Delete it when done
Two processes updating shared memory with no lock wrong totals, different on every run Race condition Synchronization (episodes 24-26)
Using kill -9 first the program can't save or clean up SIGKILL can't be handled kill (SIGTERM) first, -9 last

Mini project: build a shell pipeline echo ... | wc -w

This is exactly what your shell does for |: one pipe, two children, and dup2 to plug the pipe into standard output and standard input.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

// Runs:  echo chai samosa vada | wc -w
int main() {
    int fd[2];
    pipe(fd);
    if (fork() == 0) {              // child 1: echo, stdout -> pipe
        dup2(fd[1], 1);             // make fd 1 (stdout) point at the pipe
        close(fd[0]); close(fd[1]);
        execlp("echo", "echo", "chai", "samosa", "vada", NULL);
        perror("echo"); exit(127);
    }
    if (fork() == 0) {              // child 2: wc, stdin <- pipe
        dup2(fd[0], 0);             // make fd 0 (stdin) point at the pipe
        close(fd[0]); close(fd[1]);
        execlp("wc", "wc", "-w", NULL);
        perror("wc"); exit(127);
    }
    close(fd[0]); close(fd[1]);     // parent: close both, or wc never sees EOF
    wait(NULL); wait(NULL);
    return 0;
}

Output:

3

dup2(old, new) makes file descriptor new refer to the same pipe end as old. echo writes to fd 1 without knowing it's a pipe, and wc reads fd 0 without knowing it's a pipe. Try removing the parent's close(fd[1]): wc never sees end of file and the program hangs. Extension: build echo ... | tr a-z A-Z | wc -c with two pipes.

Practice

1. Two pipes: the parent sends a number, the child replies with its square.

Solution
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    int up[2], down[2];             // up: parent -> child, down: child -> parent
    pipe(up); pipe(down);
    if (fork() == 0) {
        close(up[1]); close(down[0]);
        int x;
        read(up[0], &x, sizeof x);
        int sq = x * x;
        write(down[1], &sq, sizeof sq);
        return 0;
    }
    close(up[0]); close(down[1]);
    int n = 12, ans;
    write(up[1], &n, sizeof n);
    read(down[0], &ans, sizeof ans);
    printf("sent %d, child replied %d\n", n, ans);
    wait(NULL);
    return 0;
}

Output: sent 12, child replied 144. One pipe per direction, because a pipe is one-way.

2. Fix "chaisamosa": send two messages through one pipe and receive them separately.

Solution

End every message with a newline and read line by line:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    int fd[2];
    pipe(fd);
    if (fork() == 0) {
        close(fd[0]);
        write(fd[1], "chai\n", 5);  // newline marks the end of a message
        write(fd[1], "samosa\n", 7);
        return 0;
    }
    close(fd[1]);
    FILE *in = fdopen(fd[0], "r");  // read line by line
    char line[64];
    while (fgets(line, sizeof line, in)) {
        line[strcspn(line, "\n")] = 0;
        printf("message: %s\n", line);
    }
    wait(NULL);
    return 0;
}

Output:

message: chai
message: samosa

The loop ends because the parent closed its write end and the child exited, so fgets sees end of file.

3. Catch Ctrl+C (SIGINT) and print "bye" before exiting.

Solution
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

void bye(int sig) {
    write(1, "bye\n", 4);           // write() is safe inside a handler
    _exit(0);
}

int main() {
    signal(SIGINT, bye);
    printf("press Ctrl+C...\n");
    fflush(stdout);
    while (1) pause();
}

Run it in a terminal and press Ctrl+C: it prints press Ctrl+C..., then bye, and exits with status 0 (tested by sending SIGINT with kill -INT). write and _exit are async-signal-safe; printf and exit are not guaranteed to be.

4. Count the words of a sentence in a child and give the result to the parent through shared memory.

Solution
#include <stdio.h>
#include <ctype.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    int *words = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE,
                      MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    const char *text = "two chai and one samosa please";
    if (fork() == 0) {              // child counts
        int n = 0, in = 0;
        for (const char *p = text; *p; p++) {
            if (!isspace((unsigned char)*p) && !in) n++;
            in = !isspace((unsigned char)*p);
        }
        *words = n;
        return 0;
    }
    wait(NULL);
    printf("child counted %d words\n", *words);
    return 0;
}

Output: child counted 6 words. Only one process writes, and the parent reads after wait, so no lock is needed here.

5. Which IPC would you choose? (a) A logger collecting lines from 5 unrelated programs on one machine. (b) Two processes sharing a 2 GB in-memory table. (c) Tell a server to reload its config. (d) A phone app asking a server for prices.

Solution

(a) A message queue or a named pipe (FIFO) / Unix domain socket: unrelated processes, whole lines. (b) Shared memory, with locks. (c) A signal (by convention many daemons reload on SIGHUP). (d) Network sockets, usually through an RPC or HTTP API.

6. A parent creates a pipe, forks, and the child writes "hi" and exits. The parent then loops while (read(fd[0], buf, 1) > 0). It prints "hi" but then hangs. Why?

Solution

The parent never closed its own copy of the write end fd[1]. EOF is reported only when all write ends are closed, so after the data is consumed, read waits for more data that may still come from the parent itself. Fix: close(fd[1]) in the parent right after fork.

Quick quiz

signal(SIGINT,  handler);
signal(SIGTERM, handler);
signal(SIGKILL, handler);
signal(SIGCHLD, handler);

For which signal does the signal call fail, because a program can't catch it? A. SIGINT B. SIGTERM C. SIGKILL D. SIGCHLD

Answer

C. SIGKILL (9). It can't be caught, blocked or ignored; signal returns SIG_ERR with errno = EINVAL ("Invalid argument").

Interview questions

  1. What is IPC and why is it needed? Processes have separate memory for protection; IPC is how cooperating processes exchange data and notifications through the kernel.
  2. Independent vs cooperating process? Independent shares nothing; cooperating affects or is affected by others (shares data).
  3. Message passing vs shared memory? Message passing copies data through the kernel (simple, safe, slower); shared memory maps one region into both (fastest, but needs synchronization).
  4. Anonymous pipe vs named pipe? Anonymous: no name, only related processes, created with pipe(). Named (FIFO): a file-system name, any processes, created with mkfifo. Both are one-way byte streams.
  5. Why can a pipe merge two messages into one read? It is a byte stream with no message boundaries.
  6. When does read on a pipe return 0? When all write ends are closed and the buffer is empty (end of file).
  7. Why is shared memory the fastest IPC? After setup there are no copies and no system calls per message; it's plain memory access.
  8. Direct vs indirect communication? Direct names the other process; indirect goes through a shared mailbox/port (e.g. a message queue).
  9. Blocking vs non-blocking send/receive? Blocking waits until delivered/available; non-blocking returns immediately.
  10. SIGTERM vs SIGKILL? SIGTERM (15) can be caught for a clean shutdown; SIGKILL (9) can't be caught, blocked or ignored and ends the process immediately.
  11. What is SIGCHLD used for? Telling a parent a child stopped or ended, typically to reap it with waitpid and avoid zombies.
  12. What is a signal handler and what should it avoid? A function run when a signal arrives; it should do very little and call only async-signal-safe functions (set a flag, write, _exit).
  13. What is a socket? How is it different from a pipe? A two-way communication endpoint; can work across machines (network sockets); a pipe is one-way and local.
  14. What is RPC? What are stubs and marshalling? Calling a function in another process/machine as if local; stubs are generated proxies that pack (marshal) and unpack arguments and results.

Glossary

Term Meaning in plain words Example
Inter-process communication (IPC) Ways for processes to exchange data or notices pipes, shared memory
Memory isolation Each process's memory is private to it the child's orders = 5 is invisible to the parent
Independent process A process that shares no data with others a calculator
Cooperating process A process that affects or is affected by others browser tab processes
Message passing IPC by sending messages through the kernel write into a pipe
Shared memory IPC through one memory region mapped into several processes mmap(MAP_SHARED)
Pipe A one-way channel in the kernel with a read end and a write end pipe(fd)
Anonymous (unnamed) pipe A pipe with no name; only related processes can share it the \| in a shell
File descriptor Small integer that refers to an open file, pipe or socket 0 stdin, 1 stdout, 2 stderr
Read end / write end fd[0] for reading / fd[1] for writing read(fd[0], ...)
Blocking A call that waits until it can complete read on an empty pipe
Byte stream A flow of bytes with no message boundaries "chai" + "samosa" → "chaisamosa"
Message boundary Where one message ends and the next begins kept by message queues
End of file (EOF) "No more data will ever come"; read returns 0 all write ends closed
dup2(old, new) Make fd new refer to what old refers to plug a pipe into stdout
Named pipe / FIFO A pipe with a name in the file system mkfifo("orders.fifo", 0666)
FIFO order First in, first out queue order
unlink Remove a name from the file system delete the FIFO's name
Message queue A kernel list of whole, typed messages msgget, msgsnd, msgrcv
Message type A number at the start of each message; receivers can filter by it 1 = drinks
IPC_NOWAIT Flag: don't wait if no message non-blocking receive
IPC_RMID Command to delete a System V IPC object msgctl(q, IPC_RMID, NULL)
POSIX Common standard API for UNIX-like systems shm_open, mq_open
System V IPC Older UNIX IPC API family msgget, shmget, semget
Direct communication Sender and receiver name each other send(P, msg)
Indirect communication Messages go through a shared mailbox send(box, msg)
Mailbox (port) A shared place messages are sent to and taken from a message queue
Synchronous (blocking) messaging Send/receive wait until done msgrcv(..., 0)
Asynchronous (non-blocking) messaging Send/receive return immediately msgrcv(..., IPC_NOWAIT)
Rendezvous Both send and receive block zero-capacity link
mmap Map memory (or a file) into a process shared counter
MAP_SHARED / MAP_ANONYMOUS Share changes with other mappers / not backed by a file the shared-memory demo
shm_open / shmget Create named shared memory (POSIX / System V) for unrelated processes
Race condition A result that depends on the timing of processes/threads two writers lose an update
Synchronization Making processes/threads take turns safely locks, semaphores
Signal A small numbered notice delivered to a process SIGINT = 2
Default action What a signal does if no handler is set end, ignore, stop
Signal handler A function run when a signal arrives on_signal
raise / kill Send a signal to yourself / to a process kill(id, SIGKILL)
SIGINT Interrupt from Ctrl+C (2) stop a running program
SIGTERM Polite termination request (15) kill PID
SIGKILL Forced termination, can't be caught (9) kill -9 PID
SIGCHLD A child stopped or ended (17 on Linux) reap with waitpid
WIFSIGNALED / WTERMSIG Was the child ended by a signal? / which one 9
Async-signal-safe Safe to call inside a signal handler write, _exit
Socket An endpoint for two-way communication socketpair, socket
Unix domain socket Socket between processes on one machine, addressed by a path AF_UNIX
Network socket Socket addressed by IP address + port AF_INET
IP address Number that identifies a machine on a network 192.168.1.5
Port Number that identifies a program on a machine 443
Client / server Sends requests / waits for and answers requests the price demo
Remote procedure call (RPC) Calling a function that runs in another process or machine getPrice(2) on a server
Stub Generated code that stands in for the remote function on each side client stub, server stub
Marshalling (serialization) Packing data into bytes for sending; unmarshalling unpacks arguments → bytes
Timeout / retry Give up after a limit / try again network calls

Summary

  • Processes have separate memory, so a global variable is not shared after fork; cooperating processes need IPC.
  • Two families: message passing (the kernel copies data; simple and safe) and shared memory (one region mapped into both; fastest, needs synchronization).
  • An anonymous pipe is a one-way byte stream between related processes; read blocks when empty, write when full, and read returns 0 at EOF when every write end is closed.
  • A named pipe (FIFO) gives a pipe a file-system name so unrelated processes can use it.
  • A message queue keeps whole typed messages; it is an indirect mailbox; receives can be blocking or non-blocking.
  • Signals are numbered notices: SIGINT (2, Ctrl+C), SIGTERM (15, polite), SIGKILL (9, can't be caught), SIGCHLD (17, child ended); handlers customise the response.
  • Sockets are two-way and work across machines; RPC wraps them so a remote call looks like a local function call.

Next episode: threads and multithreading models: what threads share, user vs kernel threads, pthreads, Java threads and thread pools.

Sources: the Linux pipe(7) man page (manpages.ubuntu.com: "Since Linux 2.6.11, the pipe capacity is 65536 bytes"; confirmed with F_GETPIPE_SZ on the test machine). Signal numbers were checked with kill -l on the test machine. Every program above was run on 30 October 2026.