Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

🏠 Back to Blog

Execution and Scheduling of Processes and Threads

How are processes made?

  • Processes are created with fork()
  • The new process created with fork() is an exact copy of its parent
    • Everything is copied from the parent except for file locks and any pending signals
    • the fork() system call has a return value of > 0 if you’re the parent, if you’re the child the value will be 0. If there is an error the return value will be less than 0.
    • fork() doesn’t copy all memory to the child at first. The child process shares the memory of the parent until the child or parent needs to write to the memory. Then the process that needs to modify the memory makes a copy of just that page and makes it’s change. This is called Copy On Write (COW).
    • On Linux, c libraries typically implement fork() by wrapping clone()

Daemon’s

  • Services / background processes
  • How to make a daemon:
    • Fork the parent process, then the parent exits, leaving the child process with parent init (pid=1)
    • Close all open file’s
    • Become the process group leader
      • a Process Group
    • Set the umask
    • Change dir to a safe place
    • Possibly ignore some signals

Process Scheduling

  • Priority determines which process gets to run
  • The kernel constantly has to decide which process to run next
  • Context switching involves moving register values out of the CPU and into memory, and loading registers for the next process to run
  • Every process has a task state associated with it. The states are:
    • TASK_RUNNING
      • Processes in the running state have a time quantum to run within. By default, 100ms.
      • The kernel checks the process time quantum every tick.
    • TASK_INTERRUPTABLE
    • TASK_UNINTERRUPTABLE
      • This is rare
    • TASK_STOPPED
    • TASK_TRACED
      • Example: tracing the process with strace
    • EXIT_ZOMBIE
    • EXIT_DEAD

Threads

  • a thread is a lightweight process
  • Threads of a process all run in the same memory address space
    • A thread has its own instruction pointer
    • The stack is not shared. Each has its own stack.
    • In linux all threads have their own PID
    • Threads will spin (spin-lock) if they are waiting to access memory that is locked by another thread
      • Processes that are spinning do not go to sleep or cede back to the kernel