KatInterview

Build a Minimal cp in C++ and Explain What the Kernel Does

System DesignModel answer
MediumModel answerSystem Designoperating-systemscppsystem-calls

Last updated

Write a C++ file-copy tool using POSIX calls, then explain page cache, write-back and kernel-assisted copy, and harden it with RAII, atomic replacement and directory support.

You are asked to reimplement the everyday Unix file-copy utility and then defend your design at a low level.

Part 1: Write the tool

Build a C++ program invoked as mycp SOURCE DEST that copies one regular file.

  • DEST may be a path that does not exist yet, an existing regular file, or an existing directory (the copy then goes inside it under SOURCE's file name).
  • Handle SOURCE and DEST being the same file.
  • Print a clear message on failure and exit with a non-zero status.
  • Every resource must be released on every code path.

Before you start, state your assumptions: which APIs you allow yourself (POSIX calls, C stdio, std::filesystem), whether directories and symlinks are in scope, whether an existing DEST is overwritten, and whether permissions and timestamps are preserved.

Part 2: Explain the machinery underneath

Describe what happens from each system call down to the disk. Cover user versus kernel mode, the cost of a system call, the effect of buffer size, the page cache, read-ahead, write-back, and what a successful write does and does not guarantee. Then explain how you would speed up copying of very large files, and when each option applies or falls back.

Part 3: Make it production quality

Explain how you guarantee descriptors are always closed and errors are reported correctly. Then describe what it takes to add recursive directory copy, symbolic links and metadata preservation, and how to ensure a failed copy never leaves a half-written DEST.

Hints

Hint 1

A single `write` may transfer fewer bytes than requested, and any call may fail with `EINTR`. Loop on both, and treat `read` returning 0 as end of file.

Hint 2

Compare `st_dev` and `st_ino` of the two files before opening DEST with `O_TRUNC`, otherwise copying a file onto itself destroys it. Also check the result of `close` on the output descriptor.

Hint 3

For performance, think about how many system calls a copy needs and where data crosses the user/kernel boundary. For safety, think about writing to a temporary file in the destination directory and renaming it into place.