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?
CodePudding user response:
Processes have their own file descriptors but those act as reference-counted pointers to shared open-file descriptions (a separate open-file description is created for each open
). The sharing of open-file descriptions is what allows, e.g., shell scripts to do stuff such as
(
/usr/bin/echo hello
/usr/bin/echo world
) > some_file
and have some_file
contain both hello
and world
without the latter overwriting the former (just like they wouldn't (without special effort) overwrite each other if they wrote to the terminal).
It also allows applications that modify terminal settings (stty
), a utility such as flock
(that places a lock into the shared file description), and possibly other stuff.