本文介紹啓動時pid文件即鎖文件的處理。
若異常宕機,導致pid文件殘留,那麼重啓時會自動將這個文件刪除嗎?
main>PostmasterMain->CreateDataDirLockFile->CreateLockFile::
for (ntries = 0;; ntries++){
// O_EXCL若存在則返回失敗,errno是17
fd = open(filename, O_RDWR | O_CREAT | O_EXCL, pg_file_create_mode);
if (fd >= 0)
break;
if ((errno != EEXIST && errno != EACCES) || ntries > 100)//重試100次
could not create lock file
fd = open(filename, O_RDONLY, pg_file_create_mode);
...
if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
...
close(fd);
//0表示檢查進程是否存在。ESRCH:沒有這個進程;EPERM:操作不允許
if (kill(other_pid, 0) == 0 ||(errno != ESRCH && errno != EPERM)){
lock file \"%s\" already exists
}
if (unlink(filename) < 0)//刪除,然後循環再試創建
...
}
//此時創建成功
if (write(fd, buffer, strlen(buffer)) != strlen(buffer))//寫入pid內容
...
if (pg_fsync(fd) != 0)
...
if (close(fd) != 0)
...
說明:
1)會以O_RDWR | O_CREAT | O_EXCL形式open,若存在的話會返回創建文件失敗。
2)若創建失敗則會重試100次
3)若文件已存在,則以只讀的形式再次open並讀取文件內容
4)解析出pid,並通過kill(pid,0)判斷進程是否存在(注意,若有子進程殘留也會判斷出來)
5)若有進程不存在,則將這個文件刪除,然後進行重試
6)創建成功後,將當前進程信息寫入文件並sync持久化。
7)最後將文件句柄關閉