3

After reading this post: https://stackoverflow.com/questions/14189944/unix-system-file-tables, I've basically understood how Linux manages the files.

But I don't know how to manage the offsets of the files.

As my understanding, one element (one line) in Open File Table maintain its own offset. For example, I have two processes A and B, which are reading one same file. So I think the case should be as below:

                      Open File Table
____________            ______________
| processA |            | offset: 12 | ------\
|   fdA    | ---------> |------------|        \         INode Table
|----------|                                   \______  ___________
                                               /        |  file   |
____________            ______________        /         |---------|
| processB |            | offset: 15 | ------/
|   fdB    | ---------> |------------|
|----------|

So, process A has its own offset in Open File Table, so does process B. In the case above, process A is reading the file at the offset 12, process B is reading the file at the offset 15.

If I'm right, now I'm confused.

Now, if I have a process, opening a file named myfile, keeps writing strings into the file. At some moment, I execute the command > myfile to empty the file. As my understanding, the process has its own offset, and the process of > myfile has another offset. > myfile only changed its own offset, but why does the writing process now start to write strings at the beginning of the file (offset equals to 0 now) after executing > myfile?

In a word, how does the writing process knows that it should change the offset after executing > myfile? Is there some offset-synchronous-mechanism?

1 Answer 1

1

In a word, how does the writing process knows that it should change the offset after executing > myfile?

It doesn’t. The file offset isn’t changed as a result of > myfile.

What happens to subsequent file operations depends on the circumstances. read returns 0 if the offset is past the end of the file. write adjusts the file offset to the end of the file if it was opened with O_APPEND; otherwise, the write happens at the requested offset, even if that results in adding missing data to the file.

1
  • OK, so the key is O_APPEND, got it.
    – Yves
    Commented Nov 12, 2020 at 8:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .