Build a Minimal cp in C++ and Explain What the Kernel Does
System DesignModel answerLast 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
I use POSIX system calls plus a little C++17. Scope is regular files for the core version. An existing DEST file is overwritten, and a directory DEST means "copy into it". I keep the source permission bits, subject to the umask. Directories, symlinks and full metadata come in Part 3.
Part 1: Implementation
Approach
statSOURCE and reject anything that is not a regular file (without-r).- If DEST is a directory, append SOURCE's base name.
- Open SOURCE and
fstatit. If DEST exists, compare(st_dev, st_ino)with SOURCE and refuse if equal. Do this before any truncation. - Open DEST with
O_WRONLY|O_CREAT|O_TRUNCand modesrc_mode & 0777. - Run a read/write loop that handles short writes and
EINTR. - Check the return value of
closeon DEST, because delayed errors (NFS, quota) can surface there.
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#include <string>
#include <system_error>
#include <vector>
#include <iostream>
class Fd {
int fd_ = -1;
public:
Fd() = default;
explicit Fd(int fd) : fd_(fd) {}
Fd(const Fd&) = delete;
Fd& operator=(const Fd&) = delete;
Fd(Fd&& o) noexcept : fd_(o.release()) {}
Fd& operator=(Fd&& o) noexcept { if (this != &o) reset(o.release()); return *this; }
~Fd() { reset(); }
int get() const { return fd_; }
int release() { int f = fd_; fd_ = -1; return f; }
void reset(int f = -1) noexcept { if (fd_ >= 0) ::close(fd_); fd_ = f; }
void close_checked() {
int f = release();
if (f >= 0 && ::close(f) != 0)
throw std::system_error(errno, std::generic_category(), "close");
}
};
[[noreturn]] void fail(const char* what) {
throw std::system_error(errno, std::generic_category(), what);
}
void copy_loop(int in, int out) {
std::vector<char> buf(1 << 20); // 1 MiB
for (;;) {
ssize_t n = ::read(in, buf.data(), buf.size());
if (n == 0) return; // EOF
if (n < 0) { if (errno == EINTR) continue; fail("read"); }
const char* p = buf.data();
while (n > 0) {
ssize_t w = ::write(out, p, n);
if (w < 0) { if (errno == EINTR) continue; fail("write"); }
p += w; n -= w;
}
}
}
int main(int argc, char** argv) try {
if (argc != 3) { std::cerr << "usage: mycp SRC DEST\n"; return 2; }
std::string src = argv[1], dst = argv[2];
struct stat ss{};
if (::stat(src.c_str(), &ss) != 0) fail(src.c_str());
if (!S_ISREG(ss.st_mode)) { std::cerr << src << ": not a regular file\n"; return 1; }
struct stat ds{};
if (::stat(dst.c_str(), &ds) == 0 && S_ISDIR(ds.st_mode)) {
auto slash = src.find_last_of('/');
dst += "/" + (slash == std::string::npos ? src : src.substr(slash + 1));
}
if (::stat(dst.c_str(), &ds) == 0 && ds.st_dev == ss.st_dev && ds.st_ino == ss.st_ino) {
std::cerr << "source and destination are the same file\n"; return 1;
}
Fd in(::open(src.c_str(), O_RDONLY | O_CLOEXEC));
if (in.get() < 0) fail(src.c_str());
Fd out(::open(dst.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, ss.st_mode & 0777));
if (out.get() < 0) fail(dst.c_str());
copy_loop(in.get(), out.get());
out.close_checked();
return 0;
} catch (const std::exception& e) {
std::cerr << "mycp: " << e.what() << '\n';
return 1;
}
Complexity: O(n) time in file size, O(B) memory for buffer size B.
Part 2: What the OS does
Boundary cost. Each read or write traps into the kernel: a mode switch, argument validation, and a copy between user and kernel memory. A call costs roughly a few hundred nanoseconds to about a microsecond, more with speculative-execution mitigations. With a 4 KiB buffer, a 10 GiB file needs about 2.6 million reads plus the same number of writes. With 128 KiB to 1 MiB it needs tens of thousands. Returns diminish past a few MiB because the buffer stops fitting in cache.
Page cache. A read goes through the VFS to the filesystem. If the pages are cached, the kernel copies them to your buffer. Otherwise it issues block I/O and sleeps. Sequential access triggers read-ahead, so later reads hit the cache. A write copies your data into cache pages, marks them dirty and returns. Background write-back flushes them later, governed by dirty-ratio thresholds and timers. Writers are throttled when too many pages are dirty.
What write guarantees. Only that the kernel accepted the bytes. It does not guarantee durability. A power loss can lose them, and I/O errors may surface later, at fsync or close. For durability call fsync(out) (and fsync the directory after a rename).
Faster copying for huge files
- Bigger buffers, plus
posix_fadvise(SEQUENTIAL)to enlarge read-ahead. For one-pass copies of data much larger than RAM,POSIX_FADV_DONTNEEDlimits cache pollution. copy_file_rangeavoids bouncing data through user space. On a local filesystem it is a kernel-internal copy, and on NFS it can be a server-side copy. Cross-filesystem support depends on kernel version, and it can return short counts, so loop. OnEXDEV,ENOSYSorEINVAL, fall back to read/write.sendfileis similar and works file to file on modern Linux. It was originally designed for file to socket.- Reflink (
ioctl(FICLONE)on Btrfs, XFS with reflink): O(1) copy-on-write clone when both files are on the same filesystem. Fall back if unsupported. - Sparse files: use
lseekwithSEEK_DATAandSEEK_HOLEto skip holes instead of writing zeros. O_DIRECTbypasses the cache but needs aligned buffers and sizes. It helps only in special cases.mmapis usually not faster for one pass and fails badly if the file is truncated underneath you (SIGBUS).
Part 3: Production hardening
Descriptor ownership. The Fd class above is move-only, so there is exactly one owner and the destructor closes on every path, including exceptions. Copying is deleted to prevent double-close. Moving transfers ownership. Destructors must not throw, so the explicit close_checked() handles the error-reporting close.
Error model. Exceptions with std::system_error keep the happy path clean. Alternatively use std::error_code returns in library code. Read errno immediately after the failing call, before anything that might overwrite it (including logging or destructors that call close). Retry on EINTR and handle EAGAIN if descriptors are non-blocking.
No half-written DEST. Write to a temporary file in the same directory (mkstemp or O_TMPFILE), copy the data, fchmod, optionally fsync, then rename over DEST. Rename is atomic within a filesystem, so readers see either the old or the new file. On any failure, unlink the temporary. The trade-off is a different inode, which breaks hard links to DEST and changes ownership unless restored. Overwriting in place preserves identity but can leave a truncated file.
Directories. Walk with std::filesystem::recursive_directory_iterator or openat/fdopendir (avoids path-resolution races). Create directories first, copy contents, then apply directory permissions last so read-only directories can still be filled. Refuse to copy a directory into itself.
Symlinks. Use lstat. By default in recursive mode, recreate the link with readlink and symlink rather than following it. Following is opt-in, and then you need cycle detection via visited (dev, ino) pairs. Preserve hard-link structure by remembering inodes with st_nlink > 1.
Metadata (the -p behavior): fchmod, fchown (usually needs privilege), futimens for timestamps, and xattrs and ACLs through flistxattr/fsetxattr. Apply timestamps last, because writing changes mtime.
Common mistakes
- Assuming
writewrites everything - Truncating DEST before checking it is the same file as SOURCE
- Ignoring the
closeresult - Leaking descriptors on early returns
- Using a tiny buffer
- Reading
errnoafter an intervening call - Following symlinks by accident in recursive copy
- Treating
writesuccess as durability