PostgreSQL 启动时会自动清理temporary-files directory

less than 1 minute read

背景

在使用数据库时,跑某些SQL的时候,如果work_mem内存不足会涉及一些临时空间的使用,比如排序,聚合,group by。

如果数据库突然crash了,或者某些原因未清除temp file。

数据库在重启的时候,会自动清理。

PostmasterMain(int argc, char *argv[])  
  call  
RemovePgTempFiles(void)  
  call  
RemovePgTempFilesInDir(const char *tmpdirname)  

代码如下:

src/backend/storage/file/fd.c

/* Process one pgsql_tmp directory for RemovePgTempFiles */  
static void  
RemovePgTempFilesInDir(const char *tmpdirname)  
{  
    DIR        *temp_dir;  
    struct dirent *temp_de;  
    char        rm_path[MAXPGPATH];  
  
    temp_dir = AllocateDir(tmpdirname);  
    if (temp_dir == NULL)  
    {  
        /* anything except ENOENT is fishy */  
        if (errno != ENOENT)  
            elog(LOG,  
                 "could not open temporary-files directory \"%s\": %m",  
                 tmpdirname);  
        return;  
    }  
  
    while ((temp_de = ReadDir(temp_dir, tmpdirname)) != NULL)  
    {  
        if (strcmp(temp_de->d_name, ".") == 0 ||  
            strcmp(temp_de->d_name, "..") == 0)  
            continue;  
  
        snprintf(rm_path, sizeof(rm_path), "%s/%s",  
                 tmpdirname, temp_de->d_name);  
  
        if (strncmp(temp_de->d_name,  
                    PG_TEMP_FILE_PREFIX,  
                    strlen(PG_TEMP_FILE_PREFIX)) == 0)  
            unlink(rm_path);    /* note we ignore any error */  
        else  
            elog(LOG,  
                 "unexpected file found in temporary-files directory: \"%s\"",  
                 rm_path);  
    }  
  
    FreeDir(temp_dir);  
}  

Flag Counter

digoal’s 大量PostgreSQL文章入口