本節目標:
1,檔案分享權限設定
- 開啟檔案核心資料結構
- 一個進程兩次開啟同一個檔案
- 兩個進程開啟同一個檔案
2,複製檔案描述符(dup、dup2、fcntl)
一,檔案分享權限設定
1,一個進程開啟兩個檔案核心資料結構
:每個進程都有一張,彼此獨立,每個檔案描述符表項都指向一個檔案表,檔案描述符0(STDIN_FILENO)、1(STDOUT_FILENO)、2(STDERR_FILENO),預設已經開啟,分別表示:標準輸入,標準輸出,標準錯誤裝置。
:每開啟一個檔案就對應一張檔案表,檔案表可以共用,當多個檔案描述符指向同一個檔案表時,檔案表中的
refcnt欄位會相應變化。檔案狀態標識:檔案的開啟模式(R,W,RW,APPEND,NOBLOCK,等),當前檔案位移量,refcnt:被引用數量,
v節點指標:指向一個v節點表。
:每個檔案對應一個,無論被被多少個進程開啟都只有一個,它包括v節點資訊(主要是stat結構體中的資訊),i節點資訊。
每個進程預設只能開啟1024個檔案描述符,當一個進程開啟一個檔案時,預設會從0開始尋找未被使用的描述符,由於0,1,2預設被佔用,所有一般從3開始使用。
2、一個進程兩次開啟同一個檔案
<sys/stat.h><sys/types.h><sys/stat.h><fcntl.h><stdlib.h><stdio.h><errno.h><.h> ERR_EXIT(m) \ ( main( argc, * buf1[] = { buf2[] = {= open( (fd1 == -= open( (fd2 == -, ,
運行結果:
1,dup
2,dup2
#include <unistd.h>
int dup(int oldfd);
int dup2(int oldfd, int newfd);
DESCRIPTION
These system calls create a copy of the file descriptor oldfd.
dup() uses the lowest-numbered unused descriptor for the new descriptor.
dup2() makes newfd be the copy of oldfd, closing newfd first if necessary, but note
the following:
* If oldfd is not a valid file descriptor, then the call fails, and newfd is not closed.
* If oldfd is a valid file descriptor, and newfd has the same value as
oldfd, then dup2() does nothing, and returns newfd.
After a successful return from one of these system calls, the old and new file descriptors may be used interchangeably. They refer to the same open file description (see open(2)) and thus share file offset and file status flags; for example, if the file offset is modified by using lseek(2) on one of the descriptors, the offset is also changed for the other.
RETURN VALUE
On success, these system calls return the new descriptor. On error, -1 is returned, and errno is set appropriately.
樣本程式:
#include <stdio.h><unistd.h><stdlib.h><fcntl.h> main(= open(( fd == -=(fd2 == -); fd3 =(fd3 == -
運行結果:
<unistd.h><stdlib.h><fcntl.h> main(= open(( fd == -= dup2(fd,(fd2 == -
運行結果:
or equal to arg and make it be a copy of fd. This is different
from dup2(2), which uses exactly the descriptor specified.
On success, the new descriptor is returned.
樣本程式:
#include <unistd.h><sys/stat.h><sys/types.h><sys/stat.h><fcntl.h><stdlib.h><stdio.h><errno.h><.h> ERR_EXIT(m) \ ( main( argc, *= open( (fd == - (fcntl(fd, F_DUPFD, ) < );
運行結果: