Copy-on-Write Simulation

medium · os, virtual-memory, cow

Copy-on-Write Simulation

Simulate copy-on-write (COW) page sharing with reference counts.

Types

type Op struct {
    Kind string // "fork", "write", "exit"
    PID  int
    Arg  int    // fork: child pid, write: page index, exit: ignored
}

func SimulateCOW(initialPages int, ops []Op) (copies int, totalPages int)

Rules

  • Start with PID 1 owning pages [0..initialPages-1].
  • Each page has a reference count.
  • fork: create child PID with the same page list; increment refcounts.
  • write: if the page is shared (refcount > 1), copy it:
    • decrement old refcount
    • create a new page id (monotonic increasing)
    • replace the page in the process
    • increment copies
  • exit: remove the process and decrement refcounts of its pages.

Output

  • copies: total number of COW copies created.
  • totalPages: number of distinct pages with refcount > 0 after all ops.

Notes

  • Inputs are valid; processes exist when referenced.
Run tests to see results
No issues detected