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?
>Solution :
Processes have their own file descriptors but those act as reference-counted pointers to shared file descriptions. The sharing of 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.
It also allows applications that modify terminal settings (stty), a utility such as flock (that places a lock into the shared filedescription), and possibly other stuff.
(BTW, you should use lseek with a filedescriptor. fseek accepts a FILE pointer).