Post

How do computer programs run

How Do Computer Programs Run? Understanding Program Execution

Curiosity: What happens when we click β€œRun” on a program? How does the operating system transform code into executing instructions?

Program execution is a complex process involving multiple layers of the operating system, from user interaction to CPU execution. Understanding this process reveals how modern computing systems work.

Program Execution Flow

graph TB
    A[User Interaction] --> B[Program Preloading]
    B --> C[Dependency Resolution]
    C --> D[Memory Allocation]
    D --> E[Runtime Initialization]
    E --> F[System Calls]
    F --> G[CPU Execution]
    G --> H[Program Termination]
    
    I[File System] --> B
    J[Shared Libraries] --> C
    K[Memory Manager] --> D
    L[JVM/.NET Runtime] --> E
    M[Von Neumann Architecture] --> G
    
    style A fill:#e1f5ff
    style B fill:#fff3cd
    style D fill:#d4edda
    style G fill:#f8d7da
    style H fill:#e7d4f8

Execution Stages

StageDescriptionKey ComponentsDuration
1. User InteractionUser initiates programGUI, CLIInstant
2. Program PreloadingOS loads executableFile system, loaderMilliseconds
3. Dependency ResolutionLoad shared librariesDLL, shared objectsMilliseconds
4. Memory AllocationAllocate memory spaceMemory managerMicroseconds
5. Runtime InitializationInitialize runtimeJVM, .NET, interpretersMilliseconds
6. System CallsCall main() functionSystem calls, APIVariable
7. CPU ExecutionExecute instructionsCPU, registersVariable
8. Program TerminationCleanup and exitResource managerMilliseconds

1. User Interaction and Command Initiation

Retrieve: User interaction triggers the execution request through the operating system.

Methods:

  • πŸ–±οΈ Double-clicking (GUI)
  • ⌨️ Command line execution
  • πŸ”— Programmatic invocation

Example:

1
2
3
4
# User double-clicks program.py
# Operating system receives execution request
# OS identifies Python interpreter
# Process begins

2. Program Preloading

Retrieve: The operating system locates and loads the executable file into memory.

Process:

  1. Locate executable file in file system
  2. Verify file permissions
  3. Load file into memory
  4. Prepare for execution

Memory Layout:

graph LR
    A[Executable File] --> B[File System]
    B --> C[Memory Loader]
    C --> D[Memory]
    
    D --> D1[Code Segment]
    D --> D2[Data Segment]
    D --> D3[Stack]
    D --> D4[Heap]
    
    style A fill:#e1f5ff
    style C fill:#fff3cd
    style D fill:#d4edda

3. Dependency Resolution and Loading

Innovate: Modern applications require shared libraries loaded dynamically.

Dependencies:

  • DLLs (Windows): Dynamic Link Libraries
  • Shared Objects (Linux):
    1
    
    .so
    
    files
  • Frameworks (macOS):
    1
    
    .framework
    
    bundles

Example:

1
2
3
4
5
6
7
8
9
10
11
12
# Python example - dependency loading
import sys
import os

# System loads required libraries
# - Python interpreter
# - Standard library modules
# - Third-party packages
# - System libraries (libc, etc.)

print(f"Python version: {sys.version}")
print(f"Platform: {sys.platform}")

4. Allocating Memory Space

Retrieve: The operating system allocates memory regions for program execution.

Memory Regions:

RegionPurposeCharacteristics
Code SegmentExecutable instructionsRead-only, shared
Data SegmentGlobal/static variablesRead-write
StackFunction calls, local variablesLIFO, fast
HeapDynamic memory allocationFlexible, slower

Memory Allocation:

1
2
3
4
5
6
7
8
9
10
11
# Example: Memory allocation in Python
import sys

# Stack allocation (automatic)
def function():
    local_var = 42  # Stack
    return local_var

# Heap allocation (dynamic)
dynamic_list = [1, 2, 3]  # Heap
print(f"Memory size: {sys.getsizeof(dynamic_list)} bytes")

5. Initializing the Runtime Environment

Retrieve: Runtime environments initialize resources needed for program execution.

Runtime Examples:

  • JVM (Java): Java Virtual Machine
  • .NET Runtime: Common Language Runtime
  • Python Interpreter: CPython, PyPy
  • Node.js: V8 engine

Initialization Steps:

graph TB
    A[Runtime Startup] --> B[Load Runtime Libraries]
    B --> C[Initialize Garbage Collector]
    C --> D[Set Up Thread Pool]
    D --> E[Initialize I/O Systems]
    E --> F[Ready for Execution]
    
    style A fill:#e1f5ff
    style F fill:#d4edda

6. System Calls and Resource Management

Innovate: The program entry point (

1
main
) begins execution, making system calls as needed.

System Calls:

  • File operations
  • Network communication
  • Process management
  • Memory management

Example:

1
2
3
4
5
6
7
8
9
10
# Program entry point
def main():
    # System calls happen here
    file = open("data.txt", "r")  # System call: open()
    data = file.read()            # System call: read()
    file.close()                  # System call: close()
    print(data)                   # System call: write()

if __name__ == "__main__":
    main()  # Entry point called

7. Von Neumann Architecture

Retrieve: The CPU executes instructions stored in memory following the Von Neumann architecture.

Architecture Components:

graph LR
    A[CPU] --> B[Control Unit]
    A --> C[ALU]
    A --> D[Registers]
    
    E[Memory] --> F[Instructions]
    E --> G[Data]
    
    B --> H[Fetch]
    H --> I[Decode]
    I --> J[Execute]
    J --> K[Write Back]
    
    style A fill:#e1f5ff
    style E fill:#fff3cd
    style H fill:#d4edda

Execution Cycle:

  1. Fetch: Get instruction from memory
  2. Decode: Understand instruction
  3. Execute: Perform operation
  4. Write Back: Store results

8. Program Termination

Retrieve: Cleanup phase releases resources and returns control to the operating system.

Cleanup Tasks:

  • Close file descriptors
  • Free network resources
  • Release memory
  • Clean up temporary files
  • Return exit code

Example:

1
2
3
4
5
6
7
8
9
10
11
12
import atexit

def cleanup():
    print("Cleaning up resources...")
    # Close files, connections, etc.

atexit.register(cleanup)

# Program execution
print("Program running...")

# When program ends, cleanup() is called automatically

Complete Execution Timeline

gantt
    title Program Execution Timeline
    dateFormat X
    axisFormat %L ms
    
    section User
    Click/Command           :0, 1
    section OS
    Load Executable        :1, 5
    Resolve Dependencies   :6, 10
    Allocate Memory        :11, 2
    section Runtime
    Initialize Runtime     :13, 5
    section Program
    Execute Main           :18, 100
    section Cleanup
    Terminate              :118, 2

Key Takeaways

Retrieve: Program execution involves eight key stages: user interaction, preloading, dependency resolution, memory allocation, runtime initialization, system calls, CPU execution, and termination.

Innovate: Understanding program execution helps optimize performance, debug issues, and design efficient applications by knowing how the operating system manages resources.

Curiosity β†’ Retrieve β†’ Innovation: Start with curiosity about how programs run, retrieve knowledge about execution stages, and innovate by optimizing each stage for better performance.

Next Steps:

  • Study operating system internals
  • Learn about memory management
  • Understand system calls
  • Optimize program startup time

 How Computer Programs Run

Translate to Korean

컴퓨터 ν”„λ‘œκ·Έλž¨μ€ μ–΄λ–»κ²Œ μ‹€ν–‰λ κΉŒμš”?

λ‹€μ΄μ–΄κ·Έλž¨μ€ 단계λ₯Ό λ³΄μ—¬μ€λ‹ˆλ‹€.

πŸ”Ή μ‚¬μš©μž μƒν˜Έ μž‘μš© 및 λͺ…λ Ή μ‹œμž‘

ν”„λ‘œκ·Έλž¨μ„ 두 번 ν΄λ¦­ν•˜λ©΄ μ‚¬μš©μžκ°€ κ·Έλž˜ν”½ μ‚¬μš©μž μΈν„°νŽ˜μ΄μŠ€λ₯Ό 톡해 μ‘μš© ν”„λ‘œκ·Έλž¨μ„ μ‹œμž‘ν•˜λ„λ‘ 운영 μ²΄μ œμ— μ§€μ‹œν•  수 μžˆμŠ΅λ‹ˆλ‹€.

πŸ”Ή ν”„λ‘œκ·Έλž¨ 사전 λ‘œλ”©

μ‹€ν–‰ μš”μ²­μ΄ μ‹œμž‘λ˜λ©΄ 운영 μ²΄μ œλŠ” λ¨Όμ € ν”„λ‘œκ·Έλž¨μ˜ μ‹€ν–‰ νŒŒμΌμ„ κ²€μƒ‰ν•©λ‹ˆλ‹€.

운영 μ²΄μ œλŠ” 파일 μ‹œμŠ€ν…œμ„ 톡해 이 νŒŒμΌμ„ μ°Ύμ•„ 싀행을 μ€€λΉ„ν•˜κΈ° μœ„ν•΄ λ©”λͺ¨λ¦¬μ— λ‘œλ“œν•©λ‹ˆλ‹€.

πŸ”Ή 쒅속성 ν•΄κ²° 및 λ‘œλ“œDependency resolution and loading

λŒ€λΆ€λΆ„μ˜ μ΅œμ‹  μ‘μš© ν”„λ‘œκ·Έλž¨μ€ DLL(동적 μ—°κ²° 라이브러리)κ³Ό 같은 μ—¬λŸ¬ 곡유 λΌμ΄λΈŒλŸ¬λ¦¬μ— μ˜μ‘΄ν•©λ‹ˆλ‹€.

πŸ”Ή λ©”λͺ¨λ¦¬ 곡간 ν• λ‹Ή

운영 μ²΄μ œλŠ” λ©”λͺ¨λ¦¬ 곡간 할당을 λ‹΄λ‹Ήν•©λ‹ˆλ‹€.

πŸ”Ή λŸ°νƒ€μž„ ν™˜κ²½ μ΄ˆκΈ°ν™”

λ©”λͺ¨λ¦¬λ₯Ό ν• λ‹Ήν•œ ν›„ 운영 체제 및 μ‹€ν–‰ ν™˜κ²½(예: Java의 JVM λ˜λŠ” .NET Framework)은 ν”„λ‘œκ·Έλž¨μ„ μ‹€ν–‰ν•˜λŠ” 데 ν•„μš”ν•œ λ‹€μ–‘ν•œ λ¦¬μ†ŒμŠ€λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

πŸ”Ή μ‹œμŠ€ν…œ 호좜 및 λ¦¬μ†ŒμŠ€ 관리

ν”„λ‘œκ·Έλž¨μ˜ μ§„μž…μ (일반적으둜 β€˜mainβ€™μ΄λΌλŠ” ν•¨μˆ˜)은 ν”„λ‘œκ·Έλž˜λ¨Έκ°€ μž‘μ„±ν•œ μ½”λ“œμ˜ 싀행을 μ‹œμž‘ν•˜κΈ° μœ„ν•΄ ν˜ΈμΆœλ©λ‹ˆλ‹€.

πŸ”Ή 폰 λ…Έμ΄λ§Œ μ•„ν‚€ν…μ²˜

Von Neumann μ•„ν‚€ν…μ²˜μ—μ„œ CPUλŠ” λ©”λͺ¨λ¦¬μ— μ €μž₯된 λͺ…령을 μ‹€ν–‰ν•©λ‹ˆλ‹€.

πŸ”Ή ν”„λ‘œκ·Έλž¨ μ’…λ£Œ

κ²°κ΅­ ν”„λ‘œκ·Έλž¨μ΄ μž‘μ—…μ„ μ™„λ£Œν•˜κ±°λ‚˜ μ‚¬μš©μžκ°€ μ‘μš© ν”„λ‘œκ·Έλž¨μ„ 적극적으둜 μ’…λ£Œν•˜λ©΄ ν”„λ‘œκ·Έλž¨μ€ 정리 단계λ₯Ό μ‹œμž‘ν•©λ‹ˆλ‹€. μ—¬κΈ°μ—λŠ” μ—΄λ € μžˆλŠ” 파일 λ””μŠ€ν¬λ¦½ν„°λ₯Ό λ‹«κ³ , λ„€νŠΈμ›Œν¬ λ¦¬μ†ŒμŠ€λ₯Ό ν™•λ³΄ν•˜κ³ , λ©”λͺ¨λ¦¬λ₯Ό μ‹œμŠ€ν…œμ— λ°˜ν™˜ν•˜λŠ” 것이 ν¬ν•¨λ©λ‹ˆλ‹€.

This post is licensed under CC BY 4.0 by the author.