再回过头来看
/* * open a file in an arbitrary directory * * NB: if the passed pathname is relative (which it usually is), * it will be interpreted relative to the process' working directory * (which should always be $PGDATA when this code is running). */ File PathNameOpenFile(FileName fileName, int fileFlags, int fileMode) { char *fnamecopy; File file; Vfd *vfdP; DO_DB(elog(LOG, "PathNameOpenFile: %s %x %o", fileName, fileFlags, fileMode)); /* * We need a malloc'd copy of the file name; fail cleanly if no room. */ fnamecopy = strdup(fileName); if (fnamecopy == NULL) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); file = AllocateVfd(); vfdP = &VfdCache[file]; while (nfile + numAllocatedDescs >= max_safe_fds) { if (!ReleaseLruFile()) break; } vfdP->fd = BasicOpenFile(fileName, fileFlags, fileMode); if (vfdP->fd < 0) { FreeVfd(file); free(fnamecopy); return -1; } ++nfile; DO_DB(elog(LOG, "PathNameOpenFile: success %d", vfdP->fd)); Insert(file); /** fprintf(stderr,"(O_CREAT) is:%x \n",O_CREAT); fprintf(stderr,"(O_TRUNC) is:%x \n",O_TRUNC); fprintf(stderr,"(O_EXCL) is:%x \n",O_EXCL); fprintf(stderr,"(O_CREAT | O_TRUNC | O_EXCL) is: %x\n", (O_CREAT | O_TRUNC | O_EXCL)); fprintf(stderr,"~(O_CREAT | O_TRUNC | O_EXCL) is: %x\n", ~(O_CREAT | O_TRUNC | O_EXCL)); fprintf(stderr,"fileFlags is %x\n", fileFlags); fprintf(stderr,"fileFlags & ~(O_CREAT | O_TRUNC | O_EXCL) is %x\n", fileFlags & ~(O_CREAT | O_TRUNC | O_EXCL)); */ vfdP->fileName = fnamecopy; /* Saved flags are adjusted to be OK for re-opening file */ vfdP->fileFlags = fileFlags & ~(O_CREAT | O_TRUNC | O_EXCL); vfdP->fileMode = fileMode; vfdP->seekPos = 0; vfdP->fileSize = 0; vfdP->fdstate = 0x0; vfdP->resowner = NULL; //fprintf(stderr,"file is: %d by proces %d \n\n",file,getpid()); return file; }
这两句,其实是干了共同的一件事:
file = AllocateVfd();
vfdP = &VfdCache[file];
AllocateVfd,是找到一个空闲的VFD描述符,其实就是定位了VFDCache内存结构数组的下标。
vfdP = &VfdCache[file],就是用下标来获得第 file+1个内存结构(VFD)的指针。
整个 PathNameOpenFile的做法也是挺怪异的,它处理的是 ,拿到一个空闲的VFD描述符。
然后对此VFD结构体进行设置,最后return的,实际是一个VfdCache内存结构数组的下标。
在PostgreSQL中,
在一个服务客户的进程的范围内(例如,启动psql客户端而导致后台建立的一个进程),
第一次访问某一个表的时候,会访问 PathNameOpenFile。第二次再访问同一表的时候,不会再次访问此PathNameOpenFile函数了(严格来说,应当是遵循某种LRU算法)。