ENع
→fork, exec and wait
الدرس 08 · Processes and threads

fork, exec and wait from the kernel's side

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

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

Every command you type in a shell starts a new program, and it always happens the same way: three system calls. fork() asks the kernel to copy the calling process, exec() swaps the program inside a process for a new one, and wait() lets the parent collect the child's result. Follow one short C program through the kernel's process table as a PCB is copied, fork returns twice, the child becomes /bin/echo without changing its ID, and a zombie waits to be collected. The lesson The process: address space, registers and the PCB introduces the PCB, and Process states: ready, running and blocked explains the states you will see change here. The Linux lesson on processes and signals shows the same ideas from the command line.

ستتعلّم

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

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

One program starts another

A running program can start another with three system calls. fork() copies the calling process. exec() swaps the program inside a process for a new one. wait() lets the first process collect the result. Each is work the kernel does.

fork()   copy me: a new process, the child
exec()   replace my program with another one
wait()   sleep until my child ends, then get its result

the whole program (C99, POSIX):

#define _POSIX_C_SOURCE 200809L  /* fork, execvp, waitpid under -std=c99 */
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    char *argv[] = {"echo", "hi", NULL};
    pid_t pid;
    int status;
    pid = fork();
    if (pid == 0)
        execvp("echo", argv);
    waitpid(pid, &status, 0);
    if (pid == 0) return 127;   /* only if exec failed */
    printf("exit %d\n", WEXITSTATUS(status));
    return 0;
}
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. One program starts another

    A running program can start another with three system calls. fork() copies the calling process. exec() swaps the program inside a process for a new one. wait() lets the first process collect the result. Each is work the kernel does.

    fork()   copy me: a new process, the child
    exec()   replace my program with another one
    wait()   sleep until my child ends, then get its result
    
    the whole program (C99, POSIX):
    
    #define _POSIX_C_SOURCE 200809L  /* fork, execvp, waitpid under -std=c99 */
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    #include <unistd.h>
    
    int main(void) {
        char *argv[] = {"echo", "hi", NULL};
        pid_t pid;
        int status;
        pid = fork();
        if (pid == 0)
            execvp("echo", argv);
        waitpid(pid, &status, 0);
        if (pid == 0) return 127;   /* only if exec failed */
        printf("exit %d\n", WEXITSTATUS(status));
        return 0;
    }
  2. The kernel keeps a record

    Our program runs as process 100. For each process the kernel keeps a record called a PCB (process control block) in its process table: the ID, the state (now running), the saved registers and where its memory is.

    PCB 100   (process control block)
      PID        100
      state      running      (running, ready, blocked, ...)
      registers  saved here while it is not running
      memory     where its code and data are
      files      its open files: 0, 1, 2
    process table = all the PCBs
  3. Line 1: fork()

    Line 1 calls fork(). Like every system call it traps into the kernel, which now works on behalf of process 100.

    line 1   pid = fork();
    process  100 asks the kernel: copy me
    trap     user mode -> kernel mode
  4. The kernel copies the process

    The kernel makes a new PCB with a new ID, 101, and copies the parent into it: its memory, its open files and its saved registers. The child is a near twin, ready to run the same code from the same spot.

    new PCB    PID 101   state ready
    memory     a copy of 100's  (Linux: copy-on-write)
    files      copies of the open file descriptors
    registers  copied: both will carry on after fork()
    parent     PID 100  is the child's parent
  5. fork() returns twice

    fork() returns twice, once in each process. The parent gets the child's ID, 101. The child gets 0. That is the only difference, and line 2, if (pid == 0), uses it to choose a path.

    in the parent   pid = 101   (the child's PID)
    in the child    pid = 0     (I am the child)
    on error        -1 in the parent, and no child
    
    which one runs first is up to the scheduler;
    here the parent does
  6. The parent waits

    In the parent pid is 101, not 0, so it skips line 3 and calls waitpid(). The child has not finished, so the kernel marks the parent blocked: it uses no CPU. The kernel runs the child instead.

    line 4     waitpid(pid, &status, 0);
    child 101  not finished yet
    PCB 100    running -> blocked
    PCB 101    ready -> running
  7. The child calls exec()

    In the child pid is 0, so it runs line 3, execvp(). The kernel throws away the child's memory, loads /bin/echo from disk in its place and starts it. Same process, same ID 101: only the program changed.

    line 3         execvp("echo", argv);
    argv       {"echo", "hi", NULL}
    execvp     finds echo on the PATH, e.g. /bin/echo
    memory     old code, data, heap and stack thrown away
               new ones loaded from the file
    PID        101   (unchanged: no new process)
    program    a.out -> /bin/echo
  8. echo runs and exits

    echo prints hi, then calls exit(0). Notice that execvp() never returned: the code that called it no longer exists. On success exec has nowhere to return to.

    echo      write(1, "hi\n", 3)   ->  screen: hi
              exit(0)                ->  kernel
    
    exec returns only if it failed (then -1);
    the full program then ends with 127
  9. A zombie, and a wake-up

    The kernel frees the child's memory and files, but keeps its PCB holding the exit status, 0. A finished process whose status nobody has collected yet is a zombie. The kernel also wakes the parent: blocked becomes ready.

    PCB 101   running -> zombie
              keeps: PID, exit status 0, usage
              memory and files freed
    PCB 100   blocked -> ready   (its child changed state)
  10. wait() collects the result

    When the parent runs again, waitpid() returns 101 and puts the exit status in status. Now the kernel deletes the zombie's PCB: the child is gone for good. The parent prints exit 0.

    waitpid    returns 101   status = 0
    PCB 101    deleted (the child is reaped)
    PCB 100    running
    printf     exit 0   (WEXITSTATUS(status))
    
    screen:
    $ ./a.out
    hi
    exit 0
  11. Why two calls, not one?

    Between fork() and exec() the child still runs the parent's code, so it can change its own setup first, such as sending its output to a file. A shell runs every command you type this way.

    $ echo hi > out.txt   the shell:
      fork()   child: close stdout, open out.txt  (fd 1)
               child: exec("echo")  -> hi goes to the file
      wait()   then show the next prompt
    
    the story as a Python simulation:
    
    table = {}                       # the kernel's process table
    
    def fork(parent, pid):           # a new PCB, a copy of the memory
        table[pid] = dict(table[parent], state="ready")
        return pid, 0                # parent sees pid, child sees 0
    
    def exec_(pid, program):         # same PCB and PID, new program
        table[pid]["program"] = program
    
    def exit_(pid, status):          # memory freed, PCB kept: zombie
        table[pid].update(state="zombie", status=status)
    
    def wait(parent, child):         # collect the status, delete the PCB
        table[parent]["state"] = "running"
        return child, table.pop(child)["status"]
    
    table[100] = {"state": "running", "program": "a.out"}
    in_parent, in_child = fork(100, 101)
    print("fork returned", in_parent, "and", in_child)
    table[100]["state"] = "blocked"  # waitpid: the child is not done
    exec_(101, "/bin/echo")
    print(101, "now runs", table[101]["program"])
    exit_(101, 0)
    print("wait returned", wait(100, 101), "table", sorted(table))
    
    prints:
    fork returned 101 and 0
    101 now runs /bin/echo
    wait returned (101, 0) table [100]

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