file descriptor

每個process有一個自己的file descriptor table,紀錄當前process的fd。

在kernel space中有一個open file table,紀錄檔案開啟的情況。
每個entry叫做open file description,其中含有offset(游標位址),rw flag等資訊,還有指向inode的pointer,inode基本上就代表某個file本人。

fd

  • 當process open()一個file時,會產生一個新的fd跟新的open file description,並且新fd會指向新open file description,新open file description再指向inode。

  • 當process A跟process Bopen()相同的file,那麼會新增各自的fd,指向不同的open file description,但兩個open file description會指向同一個inode。

  • 當process A跟process B open()不同的file,更不用說了,各自的fd指向不同的open file description,也指向不同的inode。

  • 當process A fork()一個process B出來時,A和B會有各自獨立的file descriptor table,但這些相同數字的fd(這些fd是指在fork()之前A就已經open()取得的fd)會指向相同的open file description。
    假設在fork()前,A有open()得到一個fd3,那fork()之後,B的fd3和A的fd3會指向同一個open file description。
    但如果在fork()之後,A和B各自open()一個file,這兩個新的fd4就會指向不同的open file description,也就可能會有不同的rw flag和offset(不過如果AB open()的檔案是同一個,那這兩個open file description會指向同一個inode)。

  • process有多個thread時,thread們共用process的file descriptor table。

  • process可以用dup()dup2()來複製自己的fd,新的這個fd會和舊的fd指向同一個open file description。

參考資料
https://stackoverflow.com/questions/67375028/does-opening-a-file-in-a-child-process-create-a-separate-entry-in-the-system-ope
https://kkc.github.io/2020/08/22/file-descriptor/