Operating Systems: Process Management, Inter-Process Communication, Threads, Signals, and File Descriptors

Fundamentals of Processes

  • Process Definition: A process is defined as a program in execution. It is the active entity representing the execution environment of a program, consisting of an independent memory address space and an execution context (state).

  • Process Memory Address Space Layout:

    • Program Text Segment (.text): Holds the executable machine code instructions of the program.

    • Initialized Data Segment (.data): Stores initialized global and static variables (for example, int global_var = 10;).

    • Uninitialized Data Segment (.bss): Stores uninitialized global and static variables.

    • Runtime Heap: Dynamically allocated memory during runtime via calls like malloc(). Grows upward toward higher memory addresses.

    • User Stack: Manages local variables (for example, int stack_var = 20;), function parameters, and function return addresses. Grows downward toward lower memory addresses, with the top of the stack tracked by the stack pointer register (%rsp).

    • Memory Mapped Region: Allocated for shared libraries utilized by the process.

    • Kernel Virtual Memory: Region reserved for kernel execution, storing kernel code/data, physical memory mappings, and process-specific kernel data structures (ptables, task and mm structs, and the kernel stack).

Process in Memory
  • Process Context (Execution State):

    • General-purpose CPU Registers

    • Program Counter (PC): Holds the address of the next instruction to execute.

    • Stack Pointer (SP / %rsp): Points to the current top of the stack.

    • Program Status Word (PSW): Contains status flags and condition codes.

  • Operating System Requirements for Process Management:

    • Interleaving Execution: The OS must interleave execution among multiple processes across time to maximize CPU utilization, ensuring only one process is active on a single CPU core at any given instant.

    • Resource Allocation: The OS must manage memory management and allocate system resources to processes.

    • Communication Support: The OS must provide inter-process communication (IPC) facilities.

Context Switching and CPU Control Recovery

  • Context Switch Mechanism:

    • Defines the mechanism by which the CPU switches execution from a currently running process P0P_0 to another process P1P_1.

    • Execution Steps:

    1. Save the execution context/state of process P0P_0 into its Process Control Block (PCB0\text{PCB}_0).

    2. Load the execution context/state of process P1P_1 from its Process Control Block (PCB1\text{PCB}_1).

    3. Resume execution of process P1P_1.

    • Overhead: Context-switch time is pure overhead because the system performs no useful execution work while switching contexts.

  • Process Control Block (PCB):

    • A data structure maintained by the kernel in kernel virtual memory within the process address space that stores all context and state attributes of a process.

    • PCB Fields:

    • Process State (New, Ready, Running, Waiting/Blocked, Terminated)

    • Process Identifier / Number (PID)

    • Program Counter (PC)

    • Register contents

    • Memory Management Limits (page tables, base/limit registers)

    • List of Open Files

    • Kernel data structures (ptables, task struct, mm struct, kernel stack)

Process Control Block Diagram
  • Regaining CPU Control (Solving Direct Execution Limitations):

    • Under limited direct execution, when a user process runs on the CPU, the OS kernel is inactive and cannot execute instructions.

    • Cooperative Approach:

    • The OS relies on user processes to voluntarily yield control of the CPU periodically by making system calls (for example, yield(), reading/writing I/O) or by triggering exceptions/traps (for example, divide-by-zero or illegal memory access).

    • Executing yield() transfers control to the OS kernel, which then executes a yield() return to dispatch another process.

    • Flaw: If a process enters an infinite loop without issuing a system call or triggering an exception, the OS loses control of the CPU completely.

    • Non-Cooperative Approach:

    • Employs a hardware timer device programmed to raise a hardware interrupt every y msy\,\text{ms}.

    • Upon interrupt generation, the currently running process is halted immediately.

    • Control is forcibly transferred to a pre-configured interrupt handler in the OS, enabling the kernel to preempt the running process and execute a context switch.

Process Lifecycle and State Models

  • Five-State Process Model:

    • New: The process is currently being created.

    • Ready: The process is loaded into memory and waiting to be assigned to a CPU core by the scheduler.

    • Running: Program instructions are actively executing on a CPU core.

    • Blocked (Waiting): The process cannot execute until a specific event occurs (such as I/O completion or signal delivery).

    • Exit (Terminated): The process has finished execution or was aborted; its resources are reclaimed by the system.

    • State Transitions:

    • Admit: Transition from New to Ready.

    • Dispatch: Transition from Ready to Running.

    • Timeout: Transition from Running to Ready (time quantum slice expired).

    • Event Wait: Transition from Running to Blocked (process waits for an event/IO).

    • Event Occurs: Transition from Blocked to Ready (event completes).

    • Release: Transition from Running to Exit.

Five-state process model
  • Process Queues:

    • Ready Queue: Holds all processes residing in main memory that are ready for CPU dispatch.

    • Event Queues: Individual queues (Event 1 Queue, Event 2 Queue, …, Event n Queue) holding processes waiting for specific event occurrences.

Process Queues
  • Seven-State Process Model (Swapping Support):

    • Incorporates secondary storage (disk) swap states to prevent memory starvation when all processes in main memory are blocked.

    • Blocked, Suspend: A process blocked on an event that has been swapped out of main memory to secondary storage.

    • Ready, Suspend: A process in secondary storage that is ready to run as soon as it is swapped back into main memory.

    • Additional Transitions:

    • Blocked →\rightarrow Blocked, Suspend (Suspend): Occurs when all memory processes are blocked, forcing the OS to swap out a blocked process to bring in a ready process.

    • Blocked, Suspend →\rightarrow Ready, Suspend (Event Occurs): Occurs when an event arrives for a process currently in the Blocked, Suspend state.

    • Ready, Suspend →\rightarrow Ready (Activate): Occurs when main memory has available space and no higher-priority ready processes exist in main memory.

    • Ready →\rightarrow Ready, Suspend (Suspend): Occurs when the OS must free memory for adequate system performance.

    • Running →\rightarrow Ready, Suspend: Preempted process swapped directly to secondary storage if memory pressure is severe.

    • New →\rightarrow Ready, Suspend: A newly created process allocated directly on disk due to main memory exhaustion.

Seven-state process model

Process Creation, Hierarchy, and API

  • Process Tree Hierarchy:

    • Processes are structured hierarchically in a tree formation rooted at PID 1 (init in Linux, launchd in macOS).

    • Command to display tree structure: ps auxf or pstree.

Process Tree
  • The fork() System Call:

    • Creates a new child process by duplicating the calling parent process.

    • The child process receives a deep copy of the parent process address space (including registers, PC, stack, heap, and data segments).

    • Memory address spaces post-fork are completely independent.

    • Both parent and child processes continue execution at the exact instruction following the fork() call.

    • Return Values:

    • Returns 0 inside the context of the newly created child process.

    • Returns a non-zero positive integer (representing the child's PID) inside the context of the parent process.

    • Returns -1 if the system call fails to create a process.

  • The exec() System Call Family:

    • Replaces the current process code, data, heap, and stack segments with a new executable program (for example, execlp("./child.exe", "child.exe", NULL);).

    • Retains the existing Process ID (PID) while executing the new program.

  • The wait() and waitpid() System Calls:

    • wait(int *child_status): Suspends the execution of the calling parent process until any one of its child processes terminates. Returns the PID of the terminated child.

    • waitpid(pid_t pid, int *status, int options): Suspends the calling process until the specific child process identified by pid terminates.

    • Status Inspection Macros:

    • WIFEXITED(status): Evaluates to non-zero if the child process terminated normally.

    • WEXITSTATUS(status): Extracts the exit return code of the child process.

Fork Exec Wait Diagram
  • Special Process Termination States:

    • Orphan Process: A child process actively executing whose parent process has completed execution and terminated without issuing a wait() call. Orphan processes are automatically adopted by the system initialization process init (PID 1), which reaps them upon termination.

    • Zombie Process: A child process that has completed execution/terminated but retains an entry in the kernel process table because its parent process has not yet read its exit status via wait() or waitpid().

  • Process Graph Construction & Tracing:

    • Graph Nodes represent execution events (Function Start, printf, fork, wait/waitpid).

    • Directed arrows represent control flow. Events on the same horizontal plane belong to the same process.

    • A fork() event creates a new horizontal plane for the child process.

    • Dotted lines indicate parent processes blocked in a wait() state waiting for child termination.

    • Formulas for nn Sequential fork() Calls:

    • Total processes generated: 2n2^n

    • Total child processes created: 2n−12^n - 1

    • Total output/message instances: 2n2^n

Fork with Logical Operators in C

  • Evaluation Rules and Short-Circuit Semantics:

    • fork() returns >0>0 (true) in the parent process and 00 (false) in the child process.

    • Logical AND (&&): Evaluates the right-hand expression only if the left-hand expression evaluates to non-zero (true). Short-circuits if the left expression evaluates to 00 (false).

    • Logical OR (||): Evaluates the right-hand expression only if the left-hand expression evaluates to 00 (false). Short-circuits if the left expression evaluates to non-zero (true).

    • Logical NOT (!): Inverts the boolean truth value (!0→1!0 \rightarrow 1, !(non-zero) →0\rightarrow 0).

    • Operator Precedence: ! (highest) > && > || (lowest).

  • Tracing Logical Fork Expressions:

    1. if (fork() && fork()) printf("X ");:

    • First fork(): Parent gets Child1 PID (>0>0, true); Child1 gets 00 (false).

    • Child1 short-circuits &&, skips second fork(), evaluates condition as false, and does NOT print X.

    • Parent evaluates second fork(): Creates Child2. Parent receives Child2 PID (>0>0, true); Child2 receives 00 (false).

    • Parent condition is true →\rightarrow Prints X.

    • Child2 condition is false →\rightarrow Does NOT print X.

    • Total Processes: 3 (Parent, Child1, Child2). Total X printed: 1.

Process Graph AND
  1. if (fork() || fork()) printf("X ");:

    • First fork(): Parent gets Child1 PID (>0>0, true); Child1 gets 00 (false).

    • Parent short-circuits ||, skips second fork(), evaluates condition as true →\rightarrow Prints X.

    • Child1 evaluates right side of || via second fork(): Creates Grandchild. Child1 receives Grandchild PID (>0>0, true); Grandchild receives 00 (false).

    • Child1 condition evaluates to true →\rightarrow Prints X.

    • Grandchild condition evaluates to false →\rightarrow Does NOT print X.

    • Total Processes: 3 (Parent, Child1, Grandchild). Total X printed: 2.

Process Graph OR
  1. if (!fork()) printf("X "); else printf("Y ");:

    • fork() executes: Creates Child process.

    • Child gets 00; !0 evaluates to true →\rightarrow Prints X.

    • Parent gets PID (>0>0); !PID evaluates to false →\rightarrow Executes else block, Prints Y.

    • Total Processes: 2. Output: 1 X and 1 Y.

Process Graph NOT
  1. if (fork() && fork() || fork()) printf("X ");:

    • Parsed due to precedence as ((fork() && fork()) || fork()).

    • First fork() (1): Parent gets PID (>0>0), Child1 gets 00 (false).

    • Parent executes second fork() (2): Creates Child2. Parent receives PID (>0>0); Child2 receives 00.

      • Parent (true && true) short-circuits || →\rightarrow Prints X.

      • Child2 (true && false) evaluates left of || as false, executing third fork() (3) to create Child2_1. Child2 gets PID (>0>0) →\rightarrow Prints X. Child2_1 gets 00 →\rightarrow does NOT print X.

    • Child1 from (1) short-circuits && as false, moving to right side of || and executing third fork() (3) to create Child1_1.

      • Child1 receives PID (>0>0) →\rightarrow Prints X.

      • Child1_1 receives 00 →\rightarrow does NOT print X.

    • Total Processes: 5. Total X printed: 3.

Process Graph Activity 5

Inter-Process Communication (IPC)

  • IPC Overview: Facilities allowing separate processes to communicate and synchronize actions. Basic communication model consists of Sender, Receiver, Medium, Message, and Feedback.

  • IPC Modes Comparison:

    • Network Sockets: Connect processes globally or locally across full network stacks. Powerful and flexible, but slow due to network protocol stack overhead.

    • Message Passing: Kernel-managed message exchange. Fast, structured, supports explicit blocking or non-blocking semantics.

    • Shared Memory: Maps memory directly into process address spaces. Extremely fast (zero-copy overhead during data transfer), but dangerous as user-level synchronization is required.

  • Network Sockets:

    • Used to link two processes on remote hosts (Internet Connection) or on the local host (Local Connection).

    • Addressing Parameters: IP Address (identifies host system) + Port Number (identifies target process).

    • Socket Interface Operations:

    • Server Process: socket() →\rightarrow bind() →\rightarrow listen() →\rightarrow accept() (blocks until client connection) →\rightarrow read() / write() →\rightarrow close().

    • Client Process: socket() →\rightarrow connect() →\rightarrow write() / read() →\rightarrow close().

Socket Diagram
  • Message Passing Systems:

    • Processes communicate via Send(message, recipient) and Receive(message, sender) primitives.

    • Blocking Communication (Synchronous): Sender blocks until the receiver acknowledges message receipt; receiver blocks until a message is available.

    • Non-blocking Communication (Asynchronous): Sender transmits message and resumes execution immediately; receiver reads an available message or returns immediately.

    • System Calls (<sys/ipc.h>, <sys/msg.h>):

    • int msgget(key_t key, int msgflg): Allocates or accesses a message queue corresponding to key. Flags like 0666 | IPC_CREAT. Returns message queue identifier msqid or -1 on error.

    • int msgsnd(int msqid, const void *msg_ptr, size_t msg_sz, int msgflg): Transmits message payload stored at msg_ptr. First structure field must be long mtype. msgflg = IPC_NOWAIT prevents blocking when full. Returns -1 on failure.

    • int msgrcv(int msqid, void *msg_ptr, size_t msg_sz, long int msgtype, int msgflg): Fetches message from queue msqid into buffer msg_ptr. Setting msgtype = 0 retrieves the first message; setting msgtype > 0 retrieves the first message matching that type. Returns bytes read.

    • int msgctl(int msqid, int cmd, struct msqid_ds *buf): Control operations (IPC_STAT to fetch stats, IPC_SET to set attributes, IPC_RMID to destroy the queue).

  • Shared Memory Systems:

    • A shared memory region must be explicitly established via kernel calls and mapped into address spaces.

Shared Memory Diagram
  • System Calls (<sys/shm.h>):

    • int shmget(key_t key, size_t size, int shmflg): Allocates a shared memory segment of size bytes. Returns shmid handle. Example: shmget((key_t)2345, 1024, 0666 | IPC_CREAT).

    • void *shmat(int shmid, const void *shmaddr, int shmflg): Attaches the shared segment shmid to the process address space. Setting shmaddr = NULL lets the kernel select the attach address; setting shmflg = 0 grants read-write access. Returns pointer to attached region.

    • int shmdt(const void *shmaddr): Detaches the shared memory segment starting at shmaddr from the process address space. Returns 0 on success.

    • Pipes:

  • A kernel-managed FIFO data buffer enabling unidirectional communication between processes.

  • Creation: int pipe(int fd[2]) allocates an array of two file descriptors:

    • fd[0]: Read end (Output file descriptor).

    • fd[1]: Write end (Input file descriptor).

Pipe Diagram
  • Parent-Child Pipe Mechanics:

    • Parent calls pipe(fd), then executes fork().

    • In Child (Reader): Close unused write end close(fd[1]), execute read(fd[0], buf, sizeof(buf)), then close(fd[0]).

    • In Parent (Writer): Close unused read end close(fd[0]), execute write(fd[1], "Hello", 6), then close(fd[1]).

Threads and Multithreading

  • Thread Definition: An independent sequence of execution within a process, frequently termed a lightweight process.

  • Resource Sharing Model (Single-Threaded vs. Multi-Threaded):

    • Shared Across All Threads in a Process: Memory Address Space, Global Variables, Open Files, Code Segment (.text), Data Segment (.data).

    • Private Per-Thread Execution Context: Program Counter (PC), CPU Register set, Private Stack (for local parameters/variables), Thread State.

Thread Comparison Diagram
  • Comparison: Threads vs. Processes:

    • Similarities: Threads and processes share CPU cores, execute sequentially, can create child threads/processes, maintain private PC/registers/stacks, and exist in states (Running, Ready, Blocked).

    • Dissimilarities: Processes are fully isolated and independent (different address spaces); threads share address space and resources within a process environment to assist each other.

  • Benefits of Multithreading:

    • Resource Sharing: Shares code, data, and memory space directly without IPC setup.

    • Economy: Creating and context-switching threads is significantly cheaper and faster than full process creation.

    • Responsiveness: Allows interactive applications/web servers to service background requests while maintaining user responsiveness.

    • Multiprocessor Utilization: Enables parallel execution of multiple threads across distinct CPU cores.

  • Types of Parallelism:

    • Data Parallelism: Distributes subsets of the same data across multiple CPU cores, applying the identical operation on each core.

    • Task Parallelism: Distributes unique threads across CPU cores, with each thread performing a unique operation on data.

Parallelism Diagram
  • Amdahl's Law:

    • Quantifies the performance speedup SspeedupS_{\text{speedup}} achievable on a system with NN processing cores for an application containing a serial fraction SS (0≤S≤10 \le S \le 1) and a parallelizable fraction (1−S)(1 - S):     Sspeedup=1S+1−SNS_{\text{speedup}} = \frac{1}{S + \frac{1 - S}{N}}

    • Asymptotic Limit: As N→∞N \rightarrow \infty, maximum theoretical speedup approaches 1S\frac{1}{S}.

    • Worked Example: Calculate the required parallel fraction (1−S)(1-S) across N=4N = 4 cores to yield an overall system speedup of 33:     3=1S+1−S43 = \frac{1}{S + \frac{1 - S}{4}}     S+1−S4=13S + \frac{1 - S}{4} = \frac{1}{3}     4S+1−S4=13  ⟹  3S+1=43  ⟹  3S=13  ⟹  S=19≈0.1111 (11.11%)\frac{4S + 1 - S}{4} = \frac{1}{3} \implies 3S + 1 = \frac{4}{3} \implies 3S = \frac{1}{3} \implies S = \frac{1}{9} \approx 0.1111\,\text{(11.11\%)}     Parallel portion (1−S)=1−19=89≈88.89%(1 - S) = 1 - \frac{1}{9} = \frac{8}{9} \approx 88.89\%.

  • Thread Implementation Models:

    • User-level Threads: Supported above the kernel by a user-level thread library. Creation, scheduling, and management occur without kernel knowledge. Fast, but if one thread makes a blocking system call, the entire process blocks.

User Threads
  • Kernel-level Threads: Managed directly by the OS kernel. System schedules threads independently across cores; blocking calls in one thread do not suspend other threads.

Kernel Threads
  • Thread Management Primitives: Thread_create (instantiates thread function), Thread_exit (terminates calling thread), Thread_join (blocks caller until target thread finishes), Thread_yield (voluntarily relinquishes CPU).

Signals and Signal Handling

  • Signal Definition: A small, asynchronous, software-centric notification delivered by the kernel to a process to inform it of an event.

  • Interrupt vs. Signal:

    • Interrupt: Hardware-centric notification generated by physical hardware devices to the CPU.

    • Signal: Software-centric notification managed and delivered by the OS kernel to a process.

  • Standard UNIX Signal Architecture Table:

    • ID 2 (SIGINT): Default Action: Terminate process. Trigger Event: Keyboard Interrupt (Ctrl+C).

    • ID 9 (SIGKILL): Default Action: Terminate process. Trigger Event: Force kill program. Cannot be ignored, blocked, or overridden by a custom signal handler.

    • ID 11 (SIGSEGV): Default Action: Terminate process & Dump Core. Trigger Event: Segmentation violation (invalid memory address access).

    • ID 14 (SIGALRM): Default Action: Terminate process. Trigger Event: Timer signal alarm.

    • ID 17 (SIGCHLD): Default Action: Ignore signal. Trigger Event: Child process stopped or terminated.

    • ID 20 (SIGTSTP): Default Action: Suspend Process. Trigger Event: Keyboard suspend (Ctrl+Z).

  • Signal Lifecycle: Generated (event occurs/kill() system call issued) →\rightarrow Delivered (kernel sets state bit in process context) →\rightarrow Handled (process executes default action or custom user-level signal handler).

  • Kernel Context Bit Vectors:

    • Pending Bit Vector: Bit vector where bit kk is set to 1 when signal kk has been delivered but not yet received/handled.

    • Rule: A process can hold at most one pending signal of type kk at any time. Any subsequent incoming signals of type kk while bit kk is set to 1 are silently discarded.

    • Blocked Bit Vector: Bit vector representing the process signal mask. If bit kk is set to 1, signal kk is blocked. Blocked signals can be delivered to the pending vector, but will not be received by the process until signal kk is unblocked.

Pending and Blocked Bit Vectors
  • Installing Signal Handlers (<signal.h>):

    • Function Signature: sighandler_t signal(int signum, sighandler_t handler);

    • Replaces default action for signal signum with a pointer to a custom user handler function handler.

    • When signal arrives, control transfers to the handler function, and returns to the interrupted instruction upon handler completion.

File Descriptors and I/O Redirection

  • File Descriptor Definition: Small non-negative integer values used by the OS kernel as index handles in system calls (open, read, write, close) to reference open files accessed by a process.

  • Standard File Descriptors:

    • 0 (stdin): Standard Input — Default attachment: Terminal Keyboard.

    • 1 (stdout): Standard Output — Default attachment: Terminal Screen / Output display.

    • 2 (stderr): Standard Error — Default attachment: Terminal Screen / Output display.

  • Inheritance: Child processes automatically inherit exact copies of the parent's standard file descriptors upon process creation via fork().

  • The open() System Call (<fcntl.h>, <sys/types.h>, <sys/stat.h>):

    • Requests the OS to prepare a target file for access.

    • Signature: int open(const char *pathname, int flags); (for example, fd = open("test.txt", O_RDONLY);).

    • Returns an assigned integer file descriptor on success, or -1 on error.

  • I/O Redirection Operators:

    • > or 1>: Redirects Standard Output (stdout / FD 1) to overwrite a target file (for example, myprog > outputfile).

    • >> or 1>>: Redirects Standard Output (stdout / FD 1) to append to a target file (for example, myprog 1>> file.txt).

    • <: Redirects Standard Input (stdin / FD 0) to read input from a specified file instead of the keyboard (for example, sort < file.txt).

    • 2>: Redirects Standard Error (stderr / FD 2) to a target error log file (for example, myprog 2> err.txt).

    • Combined Redirection Syntax Example: myprog < inputfile > outputfile 2> err.txt (reads input from inputfile, writes stdout to outputfile, and logs stderr to err.txt).