ENع
→Pipes and shared memory
الدرس 11 · Processes and threads

Pipes, shared memory and message passing

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

13 دقيقة11 خطوة5 أسئلةBeginner
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 11 · تفاعلي
01 / 11

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
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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
  2. Two 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 42
  3. pipe(): 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.
  4. 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)
  5. 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 way
  6. B 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)
  7. 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 aside
  8. A 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 exits
  9. B 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."
  10. 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 = 42
  11. Pipe 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

اختبار يتاح بعد الخطوة الأخيرة.