Is seek_ptr unique per file?

Viewed 56

Sorry but I didn't find clear answer to my question,

I know that each file has its own seek_ptr, let's suppose the main process opened connection to file_A then before doing anything called fork()

Then forked process reads 2 chars, which is correct?

  1. will seek_ptr be equal to 2 for both files?

  2. seek_ptr be equal to 2 for the child process and still 0 for main process?


Only if the answer is 1:

How can I open 2 files in notepad and each file has its indicator/cursor in different locations?

1 Answers

In Unix, (pid, fd) acts as a pointer into the kernel's table of open file descriptions. When a process is forked, the child process will have a different PID, call it pid2. So (pid2, fd) is a different key from (pid, fd). However, these two pointers actually point to the same open file description: fork does not fork the open file descriptions themselves. Therefore, they share a single offset. If one process seeks, it affects the other process as well. If one process reads, it affects the other process as well.

However, either process is free to call close to dissociate fd from the existing open file description, then call open to create a new open file description which may refer to the same file. After this is done, the two processes will have different open file descriptions, and seeking in one does not affect the other.

Each successful call to open always creates a new open file description.

Related