考虑这个例子(为简洁起见,我省略了头部和错误判断):
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;
}
此程序(在Linux上运行)打印
Current offset: 6
到航站楼,然后
hello
zz%
设置为dump
(%
表示缺少换行符).
为什么dump
不包含
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?