TExcelTAD

Processes

A program is a file on disk: /usr/bin/grep or C:\Windows\System32\notepad.exe. A process is a program that is running: the kernel has given it an address space, at least one thread, a table of open files or handles, an identity (user, permissions) and an ID number. Run the same program three times and you get three independent processes that share the code on disk but nothing else.

What a process owns

Both Linux and Windows keep a kernel data structure per process. Linux calls it the task_struct; Windows calls it the EPROCESS block. The fields are remarkably similar:

Resource Linux Windows
ID PID (plus a parent PID, PPID) Process ID (plus a creator's ID, rarely used)
Address space Virtual memory areas (/proc/<pid>/maps) Virtual address descriptors (VADs)
Open resources File descriptor table: small integers 0, 1, 2, … Handle table: opaque HANDLE values
Identity UID/GID, capabilities Access token (user SID, groups, privileges)
Threads One or more tasks sharing the address space One or more ETHREADs
Environment, working directory Yes Yes
Exit status 0–255 byte collected by the parent 32-bit exit code
text
          one process
  +--------------------------------+
  |  code   data   heap     stack  |  <- private virtual address space
  |--------------------------------|
  |  fd / handle table: 0 1 2 3 .. |  <- open files, pipes, sockets
  |  credentials: user, groups     |
  |  thread 1 [regs, stack ptr]    |
  |  thread 2 [regs, stack ptr]    |
  +--------------------------------+

Creating a process

This is where Linux and Windows differ the most.

Linux (and every Unix) splits creation into two system calls:

  1. fork() makes a near-exact copy of the calling process. The child gets a new PID, a copy of the parent's memory (shared copy-on-write, so it is cheap) and copies of its file descriptors.
  2. execve() replaces the program running inside the child with a new one, keeping the PID and the open files.

The gap between the two is the trick: the child can rearrange its file descriptors (redirect output to a file, connect a pipe) or drop privileges before it runs the new program. Every shell redirection you've ever typed works this way. Modern code often uses posix_spawn() or clone() with flags, which combine the steps efficiently.

Windows has one call, CreateProcess() (shells and .NET use it under the hood). You pass the executable path, the command line, the environment, the working directory and the handles the child should inherit, and Windows builds a brand-new process from scratch. There is no "copy myself" step; to redirect output you pass handles in a STARTUPINFO structure.

Linux Windows
Create fork() + execve() (or posix_spawn) CreateProcess()
Wait for exit waitpid() WaitForSingleObject(hProcess) + GetExitCodeProcess()
Terminate self exit() / _exit() ExitProcess()
Parent/child Strict tree; PID 1 adopts orphans Loose; a parent link is recorded but not enforced

A shell is the easiest way to watch fork, exec and wait at work. Every ( … ) subshell is a forked copy of the shell; & runs it in the background, and wait collects its exit status:

bash · try it yourself
( echo "child: doing some work"; exit 3 ) &
wait $!
echo "parent: child exited with status $?"

( exit 0 ) && echo "status 0 means success"
( exit 7 ) || echo "non-zero status means failure"
child: doing some work
parent: child exited with status 3
status 0 means success
non-zero status means failure

A subshell is a copy of its parent, so variable changes made inside it vanish when it exits. That is fork() semantics in action: the child got its own copy of memory.

bash · try it yourself
counter=1
( counter=99; echo "inside the child: counter=$counter" )
echo "back in the parent: counter=$counter"
inside the child: counter=99
back in the parent: counter=1

Seeing a process from the inside: /proc

On Linux every process appears as a directory under /proc. /proc/self is a shortcut to whichever process opens it, so each command below reads its own entry:

bash · try it yourself
grep -E '^(Name|State|Threads)' /proc/self/status
echo ---
head -1 /proc/self/status
cat /proc/self/comm
Name:	grep
State:	R (running)
Threads:	1
---
Name:	head
cat

grep, head and cat each saw their own name, because each is a separate process created by the shell. The same directory holds maps (the address space, see Virtual Memory & Paging), fd/ (open file descriptors), environ, cwd and much more; /proc & /sys tours it.

On Windows the same information lives in the kernel and is reached through APIs; Task Manager, tasklist, Process Explorer and PowerShell's Get-Process show it (sample output — yours will differ):

powershell
PS C:\Users\ada> Get-Process notepad | Select-Object Id, ProcessName, @{n='Threads';e={$_.Threads.Count}}, HandleCount

   Id ProcessName Threads HandleCount
   -- ----------- ------- -----------
14212 Notepad          19         711
cmd
C:\Users\ada>tasklist /fi "imagename eq notepad.exe"

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
notepad.exe                  14212 Console                    1     56,932 K

Process states

A process (strictly, each of its threads) moves through a few states:

text
             admitted              scheduler picks it
   [ new ] ----------> [ ready ] --------------------> [ running ] ----> [ terminated ]
                          ^   ^    time slice used up      |
                          |   +------------------------- --+
                          |                                |  waits for I/O, a lock, sleep()
                          +------ event happens ---- [ blocked / waiting ]

Linux shows them as letters in ps and in /proc/<pid>/status: R running or runnable, S interruptible sleep, D uninterruptible sleep (usually waiting for disk), T stopped, Z zombie. Windows thread states include Ready, Running, Waiting, Standby (chosen to run next) and Terminated.

bash · try it yourself
sleep 30 &
sleep 0.2
ps -o stat=,args= -C sleep
kill %1
S    sleep 30

Orphans and zombies

When a Linux process exits, the kernel keeps a tiny record (its exit status) until the parent calls wait(). Until then it is a zombie (Z): no memory, no code, just a row in the process table. If the parent dies first, the children become orphans and are adopted by PID 1 (systemd, or the nearest "subreaper"), which waits for them.

Windows has no zombies in the same sense: a process object stays alive while any handle to it is open, and its exit code can be read through that handle. Forgetting CloseHandle() leaks process objects in a similar way.

Process hierarchy

On Linux the tree is real: every process has exactly one parent, and pstree draws it. On Windows the parent ID is just recorded at creation; if the parent exits the ID may be reused, and nothing re-parents the child.

bash
ada@ubuntu:~$ pstree -p | head -4          # sample output — yours will differ
systemd(1)-+-ModemManager(812)-+-{ModemManager}(830)
           |-cron(790)
           |-sshd(901)---sshd(2410)---sshd(2455)---bash(2456)---pstree(2601)
           |-systemd-journal(312)

Tip: On Windows, Get-CimInstance Win32_Process | Select ProcessId, ParentProcessId, Name lists the recorded parent IDs; Process Explorer draws them as a tree.

Learn more: Threads · System Calls · ps, kill & top

Test yourself

What does fork() return to the newly created child process?

  1. The child's PID
  2. 0
  3. The parent's PID
  4. -1

Which Windows API corresponds to Linux's fork + exec pair?

  1. CreateThread
  2. ShellExecute only
  3. CreateProcess
  4. NtFork

A Linux process shows state Z in ps. What does that mean?

  1. It is swapped out
  2. It has exited but its parent has not yet collected the exit status
  3. It is waiting for disk I/O
  4. It was stopped with Ctrl+Z