Consider this example (for brevity's sake, I've omitted headers and error checking):
int main() {
int fd;
fd = open("dump", O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
if ( fork() > 0 ) {
sleep(1);
printf("Current offset: %li\n", (long)lseek(fd, 0, SEEK_CUR);
write(fd, "zz", 2);
}
else {
write(fd, "hello\n", 6);
}
close(fd);
return 0;
}
This program (run on Linux) prints
Current offset: 6
to the terminal and
hello
zz%
to dump (% signifying the lack of a newline character).
Why doesn't dump contain
zzllo
?
My thinking is, after fork, there are two file descriptors to the same process but each with its own offset. Why does writing to one descriptor affect the other?