Pipes, shared memory and message passing
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Every process has its own memory, and the kernel keeps them apart, so two programs cannot simply look at each other's data. To cooperate they need inter-process communication (IPC). Follow one small C program that forks into two processes and talks to it in two ways at once: a pipe, where the kernel copies the bytes in and out and makes the reader wait, and a page of shared memory, where the kernel sets things up once and then steps aside. The lesson User mode and kernel mode explains the system calls used here, and the Linux lesson on processes and signals shows the shell side of pipes such as grep | wc.
Two processes, two memories
Process A and process B are two running programs. Each has its own memory, its address space, and the kernel keeps them apart: A cannot read or change B's memory. To work together they need inter-process communication, or IPC.
process A own memory (its address space)
process B own memory (its address space)
fork(2): "The child process and the parent process
run in separate memory spaces."
A writes its memory -> B sees nothing
IPC = inter-process communication: a channel
the kernel sets up between themاقرأ الدرس خطوة بخطوة
Two processes, two memories
Process A and process B are two running programs. Each has its own memory, its address space, and the kernel keeps them apart: A cannot read or change B's memory. To work together they need inter-process communication, or IPC.
process A own memory (its address space) process B own memory (its address space) fork(2): "The child process and the parent process run in separate memory spaces." A writes its memory -> B sees nothing IPC = inter-process communication: a channel the kernel sets up between themTwo ways to talk
There are two basic ways. In message passing, the kernel carries a copy of the data across: a pipe works like this. In shared memory, both processes see the same page (a block of memory), and the kernel stays out of the way.
message passing data travels through the kernel pipes, POSIX message queues, sockets shared memory both see one page of memory mmap(MAP_SHARED), POSIX shm_open this example uses one of each: a pipe for the text hi\n a shared page for the number 42pipe(): the kernel makes a pipe
Before splitting in two with fork, the program called pipe(fd). The kernel made a small buffer in its own memory, with two ends: fd[1] puts bytes in and fd[0] takes them out. After fork, both processes hold both ends.
pipe(fd); a system call fd[1] the write end: bytes go in here fd[0] the read end: bytes come out here buffer in kernel memory, oldest byte first capacity 65536 bytes on Linux (16 pages) fork(); the child gets copies of fd[0] and fd[1] A, the child, will write. B, the parent, will read.B reads an empty pipe
Say B runs first and calls read(fd[0], buf, 3). That system call traps into the kernel, but the pipe is still empty, so the kernel does not return yet. It puts B to sleep: B is blocked, using no CPU, until data arrives.
B: read(fd[0], buf, 3); kernel pipe empty? yes B -> blocked (asleep, off the CPU) pipe(7): "If a process attempts to read from an empty pipe, then read(2) will block until data is available." (if A had written first, read would return at once)A writes into the pipe
A calls write(fd[1], "hi\n", 3). The system call traps into the kernel, which copies the 3 bytes h, i and newline from A's memory into the pipe buffer. That is copy one. write returns 3, and the kernel wakes B.
A: write(fd[1], "hi\n", 3); trap A -> kernel copy 1 A's memory -> pipe buffer (3 bytes) pipe: h i \n return 3 (bytes written) wake B: data is available now a full pipe would block the writer the same wayB gets the bytes
Now B's read can finish. The kernel copies the 3 bytes out of the pipe, oldest first, into buf in B's memory. That is copy two. read returns 3, and the pipe is empty again.
B: read(fd[0], buf, 3); (finishing) copy 2 pipe buffer -> B's buf (3 bytes) buf = "hi\n" return 3 (bytes read) pipe: empty each byte crossed the kernel twice: A -> kernel (write) kernel -> B (read)mmap(): one shared page
Also before fork, the program called mmap with MAP_SHARED. The kernel set aside one page, 4096 bytes, filled with zeros. After fork, that same physical page appears in A's address space and in B's.
mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); MAP_SHARED updates are seen by every process mapping the same region MAP_ANONYMOUS no file behind it; starts as zeros fork() the mapping is kept in the child one system call to set up, then the kernel steps asideA stores 42
A runs shared[0] = 42. This is a plain store instruction, not a system call. No trap, no kernel, no copy: the CPU writes 42 straight into the shared page at full speed.
A: shared[0] = 42; kind an ordinary store instruction kernel not involved shared page shared[0]: 0 -> 42 A then returns from main and exitsB waits for A
Here is the catch: nothing in the page says when A is done. If B looked too early, it would see 0. So B first calls wait(NULL), which sleeps until A has finished. Only then is the store surely there.
B: wait(NULL); kernel B sleeps until a child (A) ends A exits -> B wakes shared memory leaves the ordering to you. shm_overview(7): processes "must synchronize their access to a shared memory object, using, for example, POSIX semaphores."B loads 42
B runs x = shared[0]. Another plain instruction: it reads 42 straight from the shared page into x. The kernel never touched or copied the number on its way from A to B.
B: x = shared[0]; kind an ordinary load instruction x = 42 the whole C program prints: read 3 bytes: hi x = 42Pipe or shared memory?
A pipe costs two system calls and two copies per message, but the kernel handles the waiting and the order for you. Shared memory costs one mmap to set up, then runs at full speed, but you must synchronise yourself.
the same two channels from Python (Unix): import os, mmap r, w = os.pipe() # the kernel makes a pipe shared = mmap.mmap(-1, 4096) # one shared page (MAP_SHARED) if os.fork() == 0: # process A, the child os.write(w, b"hi\n") # message: kernel copies it in shared[0] = 42 # shared: a plain store os._exit(0) data = os.read(r, 3) # process B: kernel copies it out os.wait() # wait until A has finished print(data, shared[0]) prints: b'hi\n' 42
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01After fork, process A changes a normal variable in its memory. What does process B see?
fork gives the child its own memory space. Writes by one process do not affect the other, which is exactly why processes need IPC to share data.
02A program calls pipe(fd). Which end does a process write to?
fd[1] is the write end and fd[0] is the read end. Bytes written to fd[1] wait in the kernel's pipe buffer until someone reads them from fd[0].
03Process B calls read on a pipe that is empty. What happens?
A read on an empty pipe blocks. The blocked process uses no CPU; the kernel wakes it when bytes arrive. If every write end is closed instead, read returns 0, meaning end of file.
04How many times is each byte copied when it travels through a pipe from A to B?
write copies the bytes from A's memory into the kernel's pipe buffer, and read copies them from there into B's memory. Each copy happens inside a system call.
05A stores 42 into a shared page, and B loads it. Why does B call wait(NULL) first?
With shared memory the kernel is not involved in each access, so it does not order them. The processes must synchronise themselves, here with wait; in general with tools such as semaphores.
المسرد
- Address space
- The memory a process can see. Each process has its own, so one cannot read or change another's by accident.
- IPC
- Inter-process communication: any way for separate processes to exchange data, such as pipes, message queues, sockets or shared memory.
- Message passing
- IPC where the kernel carries a copy of the data from the sender to the receiver, for example a pipe or a POSIX message queue.
- Pipe
- A one-way channel made by pipe(): a small buffer in kernel memory with a write end, fd[1], and a read end, fd[0]. It carries a stream of bytes, oldest first.
- File descriptor
- A small number a process uses to name an open file, pipe end or device, such as fd[0] or fd[1].
- Blocked
- Asleep inside the kernel, waiting for something, such as data in a pipe. A blocked process uses no CPU until the kernel wakes it.
- Shared memory
- IPC where the kernel maps the same physical memory into two or more address spaces. After that, ordinary loads and stores reach it with no system call.
- Synchronisation
- Making processes or threads take turns in the right order, for example waiting until a writer has finished before reading.
الملاحظات والمصادر
- Which process runs first after fork is up to the scheduler. The figure shows B reaching read first, so it blocks; if A writes first, B finds the bytes waiting and read returns at once. The program prints the same either way.
- The cards show only the lines each process runs after fork. The whole program is real C99 with POSIX calls: it creates the pipe and the shared page, forks, and prints the bytes read and x.
- MAP_ANONYMOUS is not in POSIX.1-2008, but most systems support it, Linux and macOS included; POSIX code can instead name a shared memory object with shm_open and map that.
- Linux on x86-64 uses 4096-byte pages, so the 4096 bytes asked of mmap are one page; other machines may use larger pages.
- A pipe is a byte stream with no message boundaries. POSIX message queues (mq_send and mq_receive) are message passing that keeps each message whole and delivers the highest priority first.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 5: Interlude: Process API (pipes)
- MIT 6.1810, xv6: a simple, Unix-like teaching operating system (book, rev. 4): pipes
- Berkeley CS162, Lecture 5: Files and I/O, Sockets (inter-process communication, pipes)
- Linux man-pages: pipe(7)
- Linux man-pages: pipe(2)
- Linux man-pages: fork(2)
- Linux man-pages: read(2)
- Linux man-pages: wait(2)
- Linux man-pages: mmap(2)
- Linux man-pages: shm_overview(7)
- Linux man-pages: mq_overview(7)
- Linux kernel documentation: /proc/sys/fs (pipe limits)
- Python documentation: os (os.pipe, os.fork)
- Python documentation: mmap
اختبار يتاح بعد الخطوة الأخيرة.