Session 2.3: Operations on Processes

Understanding process creation, termination, hierarchy, and interprocess communication

Module 2 1.5 Hours Theory

Learning Objectives

By the end of this session, you will be able to:
  • Explain process creation mechanisms (fork(), exec())
  • Understand process termination methods
  • Analyze process hierarchy and parent-child relationships
  • Introduce interprocess communication concepts
  • Compare different IPC models
  • Identify system calls for process operations
Key Concept

Process operations enable dynamic creation and management of processes during system execution, forming the foundation for multiprogramming and concurrent execution.

Process Creation

Creating New Processes

During execution, a process may create several new processes. The creating process is called the parent process, and the new processes are called child processes.

Process Creation Scenarios
  • System initialization: Boot process creates initial processes
  • User request: Starting new applications
  • Batch job initiation: Scheduled task execution
  • Process spawning: Parent creates child for specific tasks
UNIX Process Creation: fork() System Call
fork() Example:
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid;
    
    pid = fork();
    
    if (pid == 0) {
        // Child process
        printf("I am child\n");
    } else if (pid > 0) {
        // Parent process
        printf("I am parent\n");
    } else {
        // Fork failed
        printf("Fork failed\n");
    }
    
    return 0;
}
fork() Characteristics:
  • Creates exact copy of parent process
  • Returns twice: once in parent, once in child
  • Return values:
    • Child: returns 0
    • Parent: returns child PID
    • Error: returns -1
  • Shared: Code, but separate data spaces
Program Loading: exec() System Call
exec() Family:
// Replace current process image
execl("/bin/ls", "ls", "-l", NULL);

// If exec succeeds, this line never executes
printf("exec failed\n");
execl(), execv(), execle(), execve(), execlp(), execvp()
exec() Characteristics:
  • Replaces current process image
  • Loads new program into memory
  • Same PID but different program
  • No return on success
  • Various forms for different parameter passing
Parent Process
fork()
Child Process
exec()
New Program
Windows Process Creation
CreateProcess() Example:
STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

// Create child process
if (!CreateProcess(NULL, "notepad.exe", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
    printf("CreateProcess failed\n");
    return;
}

// Wait for child to complete
WaitForSingleObject(pi.hProcess, INFINITE);

// Close handles
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);

Process Termination

Ending Process Execution
Normal Termination Reasons:
  • Normal completion: Process finishes its task
  • Error exit: Process detects error and exits
  • Fatal error: Division by zero, illegal instruction
  • Killed by another process: Parent terminates child
UNIX Termination:
exit(status)
_exit(status)
abort()
Abnormal Termination Reasons:
  • User intervention: Ctrl+C, kill command
  • Parent termination: Parent exits first
  • Resource exhaustion: Out of memory
  • System shutdown: OS terminating all processes
Windows Termination:
ExitProcess(status)
TerminateProcess(handle, code)
Resource Cleanup

When a process terminates:

  • Memory is deallocated and returned to system
  • Open files are closed automatically
  • Child processes may become orphans
  • Exit status is made available to parent
  • Process entry remains until parent reads status
Zombie Processes

When a child terminates but parent hasn't read its exit status, the child becomes a zombie process. The process entry remains in the process table until the parent calls wait().

Process Hierarchy

Parent-Child Relationships
Process Tree Structure:

Processes form a hierarchical tree structure where each process (except init) has exactly one parent but may have multiple children.

UNIX Process Tree Example:
init (PID 1)
├── systemd (PID 2)
├── kthreadd (PID 3)
├── bash (PID 1234)
│   ├── ls (PID 1235)
│   └── grep (PID 1236)
├── apache2 (PID 2000)
│   ├── apache2 (PID 2001)
│   ├── apache2 (PID 2002)
│   └── apache2 (PID 2003)
└── firefox (PID 3000)
    ├── firefox (PID 3001)
    └── firefox (PID 3002)
Process Relationships:
  • Parent Process: Creates and manages child processes
  • Child Process: Inherits certain attributes from parent
  • Sibling Processes: Share the same parent
  • Process Group: Collection of related processes
Init Process

The init process (PID 1) is the ancestor of all processes:

  • Created by kernel at boot
  • Never terminates
  • Adopts orphaned processes
  • Responsible for system shutdown
Process Synchronization:
Parent Waiting for Child:
#include <sys/wait.h>

int main() {
    pid_t pid, wpid;
    int status;
    
    pid = fork();
    
    if (pid == 0) {
        // Child process
        sleep(5);
        exit(42);
    } else {
        // Parent waits for child
        wpid = wait(&status);
        printf("Child %d exited with status %d\n", 
               wpid, WEXITSTATUS(status));
    }
    
    return 0;
}
Wait System Calls:
  • wait(&status)
    Wait for any child
  • waitpid(pid, &status, options)
    Wait for specific child
  • waitid(idtype, id, infop, options)
    More flexible waiting
Orphan Processes:

When parent terminates before child, the child becomes an orphan and is adopted by init process.

Interprocess Communication (IPC)

Process Communication Methods

Processes executing concurrently may be either independent or cooperating. Cooperating processes need mechanisms to communicate and synchronize their actions.

Why Processes Cooperate
  • Information sharing: Multiple processes access same data
  • Computation speedup: Parallel execution of subtasks
  • Modularity: Divide system into separate processes
  • Convenience: User multitasking (editing, printing, compiling)
Two Fundamental IPC Models:
Message Passing

Processes communicate by exchanging messages through the operating system.

Characteristics:
  • No shared memory between processes
  • OS handles message transfer
  • Synchronization built into communication
  • Good for distributed systems
Basic Operations:
send(destination, message)
receive(source, message)
Shared Memory

Processes communicate by reading and writing to a shared memory region.

Characteristics:
  • Fast communication - direct memory access
  • Processes control synchronization
  • OS provides shared memory facility
  • Good for high-performance applications
Basic Operations:
shmget() - create shared memory
shmat()  - attach to process
shmdt()  - detach from process
Message Passing Variations:
Communication Link Types:
  • Direct: Explicitly name sender/receiver
  • Indirect: Messages sent to/received from mailboxes
Synchronization:
  • Synchronous (blocking): Sender waits until message received
  • Asynchronous (non-blocking): Sender continues immediately
Message Size:
  • Fixed size: Simpler system design
  • Variable size: More flexible but complex
Buffering:
  • Zero capacity: No buffering (rendezvous)
  • Bounded capacity: Finite buffer size
  • Unbounded capacity: Infinite buffer (theoretical)

System Call Examples

UNIX/Linux System Calls:
Process Management:
pid_t fork(void);
int execl(const char *path, const char *arg, ...);
void exit(int status);
pid_t wait(int *status);
pid_t getpid(void);
pid_t getppid(void);
int kill(pid_t pid, int sig);
IPC - Pipes:
int pipe(int pipefd[2]);
int mkfifo(const char *pathname, mode_t mode);
IPC - Shared Memory:
int shmget(key_t key, size_t size, int shmflg);
void *shmat(int shmid, const void *shmaddr, int shmflg);
int shmdt(const void *shmaddr);
Windows System Calls:
Process Management:
BOOL CreateProcess(...);
VOID ExitProcess(UINT uExitCode);
BOOL TerminateProcess(HANDLE hProcess, UINT uExitCode);
DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds);
DWORD GetCurrentProcessId(void);
IPC - Named Pipes:
HANDLE CreateNamedPipe(...);
BOOL ConnectNamedPipe(HANDLE hNamedPipe, LPOVERLAPPED lpOverlapped);
IPC - Shared Memory:
HANDLE CreateFileMapping(...);
LPVOID MapViewOfFile(...);

Session Summary

Key Takeaways:
  • Processes can create child processes using fork() (UNIX) or CreateProcess() (Windows)
  • exec() family replaces process image with new program
  • Process termination involves resource cleanup and status reporting
  • Processes form hierarchical tree structures with parent-child relationships
  • IPC enables cooperation between processes through message passing or shared memory
  • Different operating systems provide different system calls for process operations
Important Concepts:
  • fork(): Creates exact copy of parent process
  • exec(): Loads new program into existing process
  • wait(): Parent synchronizes with child termination
  • Zombie processes: Terminated children waiting for parent to read status
  • Orphan processes: Children whose parents have terminated
  • Message passing vs Shared memory: Two fundamental IPC models
Next Session

Session 2.4: Concurrency and Threading
Concurrency concepts, interacting processes, multithreading models, and benefits of multithreading

Study Tips:
  • Practice writing simple fork() and exec() programs
  • Understand the difference between process creation and program loading
  • Draw process trees to visualize parent-child relationships
  • Compare message passing vs shared memory trade-offs
  • Understand zombie and orphan process concepts