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,taskandmmstructs, and the kernel stack).

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 to another process .
Execution Steps:
Save the execution context/state of process into its Process Control Block ().
Load the execution context/state of process from its Process Control Block ().
Resume execution of process .
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,taskstruct,mmstruct, kernel stack)

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 ayield()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 .
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.

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.

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:
BlockedBlocked, 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, SuspendReady, Suspend(Event Occurs): Occurs when an event arrives for a process currently in the Blocked, Suspend state.Ready, SuspendReady(Activate): Occurs when main memory has available space and no higher-priority ready processes exist in main memory.ReadyReady, Suspend(Suspend): Occurs when the OS must free memory for adequate system performance.RunningReady, Suspend: Preempted process swapped directly to secondary storage if memory pressure is severe.NewReady, Suspend: A newly created process allocated directly on disk due to main memory exhaustion.

Process Creation, Hierarchy, and API
Process Tree Hierarchy:
Processes are structured hierarchically in a tree formation rooted at PID 1 (
initin Linux,launchdin macOS).Command to display tree structure:
ps auxforpstree.

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
0inside 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
-1if 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()andwaitpid()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 bypidterminates.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.

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 processinit(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()orwaitpid().
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 Sequential
fork()Calls:Total processes generated:
Total child processes created:
Total output/message instances:
Fork with Logical Operators in C
Evaluation Rules and Short-Circuit Semantics:
fork()returns (true) in the parent process and (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 (false).Logical OR (
||): Evaluates the right-hand expression only if the left-hand expression evaluates to (false). Short-circuits if the left expression evaluates to non-zero (true).Logical NOT (
!): Inverts the boolean truth value (,!(non-zero)).Operator Precedence:
!(highest) >&&>||(lowest).
Tracing Logical Fork Expressions:
if (fork() && fork()) printf("X ");:
First
fork(): Parent gets Child1 PID (, true); Child1 gets (false).Child1 short-circuits
&&, skips secondfork(), evaluates condition as false, and does NOT printX.Parent evaluates second
fork(): Creates Child2. Parent receives Child2 PID (, true); Child2 receives (false).Parent condition is true Prints
X.Child2 condition is false Does NOT print
X.Total Processes: 3 (Parent, Child1, Child2). Total
Xprinted: 1.

if (fork() || fork()) printf("X ");:First
fork(): Parent gets Child1 PID (, true); Child1 gets (false).Parent short-circuits
||, skips secondfork(), evaluates condition as true PrintsX.Child1 evaluates right side of
||via secondfork(): Creates Grandchild. Child1 receives Grandchild PID (, true); Grandchild receives (false).Child1 condition evaluates to true Prints
X.Grandchild condition evaluates to false Does NOT print
X.Total Processes: 3 (Parent, Child1, Grandchild). Total
Xprinted: 2.

if (!fork()) printf("X "); else printf("Y ");:fork()executes: Creates Child process.Child gets ;
!0evaluates to true PrintsX.Parent gets PID ();
!PIDevaluates to false Executeselseblock, PrintsY.Total Processes: 2. Output: 1
Xand 1Y.

if (fork() && fork() || fork()) printf("X ");:Parsed due to precedence as
((fork() && fork()) || fork()).First
fork()(1): Parent gets PID (), Child1 gets (false).Parent executes second
fork()(2): Creates Child2. Parent receives PID (); Child2 receives .Parent
(true && true)short-circuits||PrintsX.Child2
(true && false)evaluates left of||as false, executing thirdfork()(3) to create Child2_1. Child2 gets PID () PrintsX. Child2_1 gets does NOT printX.
Child1 from (1) short-circuits
&&as false, moving to right side of||and executing thirdfork()(3) to create Child1_1.Child1 receives PID () Prints
X.Child1_1 receives does NOT print
X.
Total Processes: 5. Total
Xprinted: 3.

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()bind()listen()accept()(blocks until client connection)read()/write()close().Client Process:
socket()connect()write()/read()close().

Message Passing Systems:
Processes communicate via
Send(message, recipient)andReceive(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 tokey. Flags like0666 | IPC_CREAT. Returns message queue identifiermsqidor-1on error.int msgsnd(int msqid, const void *msg_ptr, size_t msg_sz, int msgflg): Transmits message payload stored atmsg_ptr. First structure field must belong mtype.msgflg = IPC_NOWAITprevents blocking when full. Returns-1on failure.int msgrcv(int msqid, void *msg_ptr, size_t msg_sz, long int msgtype, int msgflg): Fetches message from queuemsqidinto buffermsg_ptr. Settingmsgtype = 0retrieves the first message; settingmsgtype > 0retrieves the first message matching that type. Returns bytes read.int msgctl(int msqid, int cmd, struct msqid_ds *buf): Control operations (IPC_STATto fetch stats,IPC_SETto set attributes,IPC_RMIDto destroy the queue).
Shared Memory Systems:
A shared memory region must be explicitly established via kernel calls and mapped into address spaces.

System Calls (
<sys/shm.h>):int shmget(key_t key, size_t size, int shmflg): Allocates a shared memory segment ofsizebytes. Returnsshmidhandle. Example:shmget((key_t)2345, 1024, 0666 | IPC_CREAT).void *shmat(int shmid, const void *shmaddr, int shmflg): Attaches the shared segmentshmidto the process address space. Settingshmaddr = NULLlets the kernel select the attach address; settingshmflg = 0grants read-write access. Returns pointer to attached region.int shmdt(const void *shmaddr): Detaches the shared memory segment starting atshmaddrfrom the process address space. Returns0on 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).

Parent-Child Pipe Mechanics:
Parent calls
pipe(fd), then executesfork().In Child (Reader): Close unused write end
close(fd[1]), executeread(fd[0], buf, sizeof(buf)), thenclose(fd[0]).In Parent (Writer): Close unused read end
close(fd[0]), executewrite(fd[1], "Hello", 6), thenclose(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.

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.

Amdahl's Law:
Quantifies the performance speedup achievable on a system with processing cores for an application containing a serial fraction () and a parallelizable fraction :
Asymptotic Limit: As , maximum theoretical speedup approaches .
Worked Example: Calculate the required parallel fraction across cores to yield an overall system speedup of : Parallel portion .
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.

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.

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)Delivered(kernel sets state bit in process context)Handled(process executes default action or custom user-level signal handler).Kernel Context Bit Vectors:
Pending Bit Vector: Bit vector where bit is set to
1when signal has been delivered but not yet received/handled.Rule: A process can hold at most one pending signal of type at any time. Any subsequent incoming signals of type while bit is set to
1are silently discarded.Blocked Bit Vector: Bit vector representing the process signal mask. If bit is set to
1, signal is blocked. Blocked signals can be delivered to the pending vector, but will not be received by the process until signal is unblocked.

Installing Signal Handlers (
<signal.h>):Function Signature:
sighandler_t signal(int signum, sighandler_t handler);Replaces default action for signal
signumwith a pointer to a custom user handler functionhandler.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
-1on error.
I/O Redirection Operators:
>or1>: Redirects Standard Output (stdout/ FD 1) to overwrite a target file (for example,myprog > outputfile).>>or1>>: 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 frominputfile, writesstdouttooutputfile, and logsstderrtoerr.txt).