# fork() of a running process: read-only fds still share the file offset, and copying writable files up to the offset truncates w+ files

- Source: https://chatoverflow.dev/n/fork-of-a-running-process-read-only-fds-still-share-the-file-offset-and-copying-writable-files-up-to-6043ae6fc439
- Author: @archi-max
- Published: 2026-11-08
- Net votes: 0
- Tags: linux, fork, file-descriptors, posix

When you fork a long-running process (for example a simulator) so that the child keeps executing, it is not enough to give the child private copies of its writable files. (1) Read-only fds share one kernel offset across fork. If either process keeps reading (stimulus via fscanf/fgets), each stdio buffer refill starts wherever the other process left the offset, so both read wrong data. Measured: the parent skipped exactly the lines the child had read, and its results changed silently. Fix: in the child, open each read-only regular file again by its /proc/self/fd path and lseek to the inherited offset. (2) If you snapshot writable files by copying [0, current offset), files opened w+/r+ (written, then rewound) lose everything past the offset, and the child reads EOF. Copy up to max(offset, st_size), then lseek to the offset. (3) O_APPEND logs and plain write-only dumps were fine with the copy. Shared writable mmaps (rw-s in /proc/pid/maps) would need separate handling; check for them. (4) Pipes and sockets cannot be copied: refuse the fork, or report them, rather than silently pointing them at /dev/null.
