70#define DEFAULT_WAIT 60
72#define WAITS_PER_SEC 10
74 "WAITS_PER_SEC must divide USECS_PER_SEC evenly");
81static int sig = SIGINT;
107static DWORD pgctl_start_type = SERVICE_AUTO_START;
108static SERVICE_STATUS status;
109static SERVICE_STATUS_HANDLE hStatus = (SERVICE_STATUS_HANDLE) 0;
110static HANDLE shutdownHandles[2];
112#define shutdownEvent shutdownHandles[0]
113#define postmasterProcess shutdownHandles[1]
121static
void set_sig(
char *signame);
135#include <versionhelpers.h>
136static bool pgwin32_IsInstalled(SC_HANDLE);
137static char *pgwin32_CommandLine(
bool);
138static void pgwin32_doRegister(
void);
139static void pgwin32_doUnregister(
void);
140static void pgwin32_SetServiceStatus(DWORD);
141static void WINAPI pgwin32_ServiceHandler(DWORD);
142static void WINAPI pgwin32_ServiceMain(DWORD, LPTSTR *);
143static void pgwin32_doRunAsService(
void);
144static int CreateRestrictedProcess(
char *cmd, PROCESS_INFORMATION *processInfo,
bool as_service);
145static PTOKEN_PRIVILEGES GetPrivilegesToDelete(HANDLE hToken);
148static pid_t
get_pgpid(
bool is_status_request);
149static char **
readfile(
const char *path,
int *numlines);
159#if defined(HAVE_GETRLIMIT)
168write_eventlog(
int level,
const char *line)
170 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
172 if (
silent_mode && level == EVENTLOG_INFORMATION_TYPE)
175 if (evtHandle == INVALID_HANDLE_VALUE)
177 evtHandle = RegisterEventSource(NULL,
179 if (evtHandle == NULL)
181 evtHandle = INVALID_HANDLE_VALUE;
186 ReportEvent(evtHandle,
221 vsnprintf(errbuf,
sizeof(errbuf), fmt, ap);
223 write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
267 exit(is_status_request ? 4 : 1);
272 write_stderr(
_(
"%s: directory \"%s\" is not a database cluster directory\n"),
274 exit(is_status_request ? 4 : 1);
290 if (fscanf(pidf,
"%d", &pid) != 1)
293 if (ftell(pidf) == 0 && feof(pidf))
349 result = (
char **)
pg_malloc(
sizeof(
char *));
372 if (buffer[
i] ==
'\n')
377 result = (
char **)
pg_malloc((nlines + 1) *
sizeof(
char *));
385 if (buffer[
i] ==
'\n')
387 int slen = &buffer[
i] - linebegin;
390 memcpy(linebuf, linebegin, slen);
392 if (slen > 0 && linebuf[slen - 1] ==
'\r')
394 linebuf[slen] =
'\0';
395 result[n++] = linebuf;
396 linebegin = &buffer[
i + 1];
413 char *curr_line = NULL;
419 while ((curr_line = optlines[
i++]))
479 write_stderr(
_(
"%s: could not start server due to setsid() failure: %m\n"),
491 cmd =
psprintf(
"exec \"%s\" %s%s < \"%s\" >> \"%s\" 2>&1",
495 cmd =
psprintf(
"exec \"%s\" %s%s < \"%s\" 2>&1",
498 (void) execl(
"/bin/sh",
"/bin/sh",
"-c", cmd, (
char *) NULL);
514 PROCESS_INFORMATION pi;
518 comspec = getenv(
"COMSPEC");
557 cmd =
psprintf(
"\"%s\" /C \"\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1\"",
561 cmd =
psprintf(
"\"%s\" /C \"\"%s\" %s%s < \"%s\" 2>&1\"",
564 if (!CreateRestrictedProcess(cmd, &pi,
false))
566 write_stderr(
_(
"%s: could not start server: error code %lu\n"),
567 progname, (
unsigned long) GetLastError());
571 postmasterProcess = pi.hProcess;
572 CloseHandle(pi.hThread);
573 return pi.dwProcessId;
667 pm_died = (waitpid(pm_pid, &exitstatus, WNOHANG) == pm_pid);
669 pm_died = (WaitForSingleObject(postmasterProcess, 0) == WAIT_OBJECT_0);
694 status.dwWaitHint += 6000;
695 status.dwCheckPoint++;
696 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
729 if (
kill(pid, 0) != 0)
766 if (
kill(pid, 0) != 0)
781#if defined(HAVE_GETRLIMIT)
787 getrlimit(RLIMIT_CORE, &lim);
788 if (lim.rlim_max == 0)
790 write_stderr(
_(
"%s: cannot set core file size limit; disallowed by hard limit\n"),
794 else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
796 lim.rlim_cur = lim.rlim_max;
797 setrlimit(RLIMIT_CORE, &lim);
814 if (optlines == NULL)
819 else if (numlines != 1)
821 write_stderr(
_(
"%s: option file \"%s\" must have exactly one line\n"),
830 optline = optlines[0];
836 if ((arg1 = strstr(optline,
" \"")) != NULL)
863 write_stderr(
_(
"%s: could not send stop signal (PID: %d): %m\n"),
871 pqsignal(postgres_signal_arg, SIG_DFL);
872 raise(postgres_signal_arg);
891 write_stderr(
_(
"program \"%s\" is needed by %s but was not found in the same directory as \"%s\"\n"),
894 write_stderr(
_(
"program \"%s\" was found by \"%s\" but was not the same version as %s\n"),
920 cmd =
psprintf(
"\"%s\" %s%s > \"%s\"",
924 if (system(cmd) != 0)
942 "trying to start server anyway\n"),
955#if defined(HAVE_GETRLIMIT)
969 snprintf(env_var,
sizeof(env_var),
"%d", (
int) getppid());
970 setenv(
"PG_GRANDPARENT_PID", env_var, 1);
989 print_msg(
_(
"waiting for server to start..."));
1005 print_msg(
_(
"server shut down because of recovery target settings\n"));
1010 "Examine the log output.\n"),
1021 CloseHandle(postmasterProcess);
1022 postmasterProcess = INVALID_HANDLE_VALUE;
1044 "single-user server is running (PID: %d)\n"),
1062 print_msg(
_(
"waiting for server to shut down..."));
1070 write_stderr(
_(
"HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1071 "waiting for session-initiated disconnection.\n"));
1107 "single-user server is running (PID: %d)\n"),
1109 write_stderr(
_(
"Please terminate the single-user server and try again.\n"));
1122 print_msg(
_(
"waiting for server to shut down..."));
1131 write_stderr(
_(
"HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1132 "waiting for session-initiated disconnection.\n"));
1141 write_stderr(
_(
"%s: old server process (PID: %d) seems to be gone\n"),
1165 "single-user server is running (PID: %d)\n"),
1167 write_stderr(
_(
"Please terminate the single-user server and try again.\n"));
1173 write_stderr(
_(
"%s: could not send reload signal (PID: %d): %m\n"),
1204 "single-user server is running (PID: %d)\n"),
1212 "server is not in standby mode\n"),
1221 write_stderr(
_(
"%s: could not create promote signal file \"%s\": %m\n"),
1225 if (fclose(prmfile))
1227 write_stderr(
_(
"%s: could not write promote signal file \"%s\": %m\n"),
1235 write_stderr(
_(
"%s: could not send promote signal (PID: %d): %m\n"),
1238 write_stderr(
_(
"%s: could not remove promote signal file \"%s\": %m\n"),
1245 print_msg(
_(
"waiting for server to promote..."));
1270 FILE *logrotatefile;
1285 "single-user server is running (PID: %d)\n"),
1294 write_stderr(
_(
"%s: could not create log rotation signal file \"%s\": %m\n"),
1298 if (fclose(logrotatefile))
1300 write_stderr(
_(
"%s: could not write log rotation signal file \"%s\": %m\n"),
1308 write_stderr(
_(
"%s: could not send log rotation signal (PID: %d): %m\n"),
1311 write_stderr(
_(
"%s: could not remove log rotation signal file \"%s\": %m\n"),
1316 print_msg(
_(
"server signaled to rotate log file\n"));
1337 if (pid == getpid())
1340 if (pid == getppid())
1343 if (
kill(pid, 0) == 0)
1363 printf(
_(
"%s: single-user server is running (PID: %d)\n"),
1377 printf(
_(
"%s: server is running (PID: %d)\n"),
1381 if (optlines != NULL)
1383 for (curr_line = optlines; *curr_line != NULL; curr_line++)
1410 write_stderr(
_(
"%s: could not send signal %d (PID: %d): %m\n"),
1419pgwin32_IsInstalled(SC_HANDLE hSCM)
1422 bool bResult = (hService != NULL);
1425 CloseServiceHandle(hService);
1430pgwin32_CommandLine(
bool registration)
1457 if (strlen(cmdPath) < 4 ||
1459 snprintf(cmdPath + strlen(cmdPath),
sizeof(cmdPath) - strlen(cmdPath),
1510 return cmdLine->
data;
1514pgwin32_doRegister(
void)
1517 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1524 if (pgwin32_IsInstalled(hSCM))
1526 CloseServiceHandle(hSCM);
1532 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1533 pgctl_start_type, SERVICE_ERROR_NORMAL,
1534 pgwin32_CommandLine(
true),
1537 CloseServiceHandle(hSCM);
1538 write_stderr(
_(
"%s: could not register service \"%s\": error code %lu\n"),
1540 (
unsigned long) GetLastError());
1543 CloseServiceHandle(hService);
1544 CloseServiceHandle(hSCM);
1548pgwin32_doUnregister(
void)
1551 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1558 if (!pgwin32_IsInstalled(hSCM))
1560 CloseServiceHandle(hSCM);
1567 CloseServiceHandle(hSCM);
1568 write_stderr(
_(
"%s: could not open service \"%s\": error code %lu\n"),
1570 (
unsigned long) GetLastError());
1573 if (!DeleteService(hService))
1575 CloseServiceHandle(hService);
1576 CloseServiceHandle(hSCM);
1577 write_stderr(
_(
"%s: could not unregister service \"%s\": error code %lu\n"),
1579 (
unsigned long) GetLastError());
1582 CloseServiceHandle(hService);
1583 CloseServiceHandle(hSCM);
1587pgwin32_SetServiceStatus(DWORD currentState)
1589 status.dwCurrentState = currentState;
1590 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1594pgwin32_ServiceHandler(DWORD request)
1598 case SERVICE_CONTROL_STOP:
1599 case SERVICE_CONTROL_SHUTDOWN:
1606 status.dwWaitHint = 10000;
1607 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1608 SetEvent(shutdownEvent);
1611 case SERVICE_CONTROL_PAUSE:
1613 status.dwWaitHint = 5000;
1618 case SERVICE_CONTROL_CONTINUE:
1619 case SERVICE_CONTROL_INTERROGATE:
1626pgwin32_ServiceMain(DWORD argc, LPTSTR *argv)
1628 PROCESS_INFORMATION pi;
1632 status.dwWin32ExitCode = S_OK;
1633 status.dwCheckPoint = 0;
1634 status.dwWaitHint = 60000;
1635 status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1636 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
1637 status.dwServiceSpecificExitCode = 0;
1638 status.dwCurrentState = SERVICE_START_PENDING;
1640 memset(&pi, 0,
sizeof(pi));
1645 if ((hStatus = RegisterServiceCtrlHandler(
register_servicename, pgwin32_ServiceHandler)) == (SERVICE_STATUS_HANDLE) 0)
1648 if ((shutdownEvent = CreateEvent(NULL,
true,
false, NULL)) == NULL)
1652 pgwin32_SetServiceStatus(SERVICE_START_PENDING);
1653 if (!CreateRestrictedProcess(pgwin32_CommandLine(
false), &pi,
true))
1655 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1659 postmasterProcess = pi.hProcess;
1660 CloseHandle(pi.hThread);
1664 write_eventlog(EVENTLOG_INFORMATION_TYPE,
_(
"Waiting for server startup...\n"));
1667 write_eventlog(EVENTLOG_ERROR_TYPE,
_(
"Timed out waiting for server startup\n"));
1668 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1671 write_eventlog(EVENTLOG_INFORMATION_TYPE,
_(
"Server started and accepting connections\n"));
1674 pgwin32_SetServiceStatus(SERVICE_RUNNING);
1677 ret = WaitForMultipleObjects(2, shutdownHandles, FALSE, INFINITE);
1679 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1688 int maxShutdownCheckPoint = status.dwCheckPoint + 12;
1696 while (WaitForSingleObject(postmasterProcess, 5000) == WAIT_TIMEOUT && status.dwCheckPoint < maxShutdownCheckPoint)
1698 status.dwCheckPoint++;
1699 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1704 case (WAIT_OBJECT_0 + 1):
1712 CloseHandle(shutdownEvent);
1713 CloseHandle(postmasterProcess);
1715 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1719pgwin32_doRunAsService(
void)
1724 if (StartServiceCtrlDispatcher(st) == 0)
1726 write_stderr(
_(
"%s: could not start service \"%s\": error code %lu\n"),
1728 (
unsigned long) GetLastError());
1745InheritStdHandles(STARTUPINFO *si)
1747 si->dwFlags |= STARTF_USESTDHANDLES;
1748 si->hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1749 if (si->hStdInput == NULL)
1750 si->hStdInput = INVALID_HANDLE_VALUE;
1751 si->hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1752 if (si->hStdOutput == NULL)
1753 si->hStdOutput = INVALID_HANDLE_VALUE;
1754 si->hStdError = GetStdHandle(STD_ERROR_HANDLE);
1755 if (si->hStdError == NULL)
1756 si->hStdError = INVALID_HANDLE_VALUE;
1769CreateRestrictedProcess(
char *cmd, PROCESS_INFORMATION *processInfo,
bool as_service)
1775 HANDLE restrictedToken;
1777 SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
1778 SID_AND_ATTRIBUTES dropSids[2];
1779 PTOKEN_PRIVILEGES delPrivs;
1781 ZeroMemory(&si,
sizeof(si));
1790 InheritStdHandles(&si);
1793 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
1799 write_stderr(
_(
"%s: could not open process token: error code %lu\n"),
1800 progname, (
unsigned long) GetLastError());
1805 ZeroMemory(&dropSids,
sizeof(dropSids));
1806 if (!AllocateAndInitializeSid(&NtAuthority, 2,
1807 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
1808 0, &dropSids[0].Sid) ||
1809 !AllocateAndInitializeSid(&NtAuthority, 2,
1810 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
1811 0, &dropSids[1].Sid))
1813 write_stderr(
_(
"%s: could not allocate SIDs: error code %lu\n"),
1814 progname, (
unsigned long) GetLastError());
1819 delPrivs = GetPrivilegesToDelete(origToken);
1820 if (delPrivs == NULL)
1824 b = CreateRestrictedToken(origToken,
1826 sizeof(dropSids) /
sizeof(dropSids[0]),
1828 delPrivs->PrivilegeCount, delPrivs->Privileges,
1833 FreeSid(dropSids[1].Sid);
1834 FreeSid(dropSids[0].Sid);
1835 CloseHandle(origToken);
1839 write_stderr(
_(
"%s: could not create restricted token: error code %lu\n"),
1840 progname, (
unsigned long) GetLastError());
1845 r = CreateProcessAsUser(restrictedToken, NULL, cmd, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, processInfo);
1847 if (IsProcessInJob(processInfo->hProcess, NULL, &inJob))
1859 sprintf(jobname,
"PostgreSQL_%lu",
1860 (
unsigned long) processInfo->dwProcessId);
1862 job = CreateJobObject(NULL, jobname);
1865 JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit;
1866 JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions;
1867 JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit;
1869 ZeroMemory(&basicLimit,
sizeof(basicLimit));
1870 ZeroMemory(&uiRestrictions,
sizeof(uiRestrictions));
1871 ZeroMemory(&securityLimit,
sizeof(securityLimit));
1873 basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS;
1874 basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS;
1875 SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit,
sizeof(basicLimit));
1877 uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS |
1878 JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_READCLIPBOARD |
1879 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD;
1881 SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions,
sizeof(uiRestrictions));
1883 securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN;
1884 securityLimit.JobToken = restrictedToken;
1885 SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit,
sizeof(securityLimit));
1887 AssignProcessToJobObject(job, processInfo->hProcess);
1892 CloseHandle(restrictedToken);
1894 ResumeThread(processInfo->hThread);
1908static PTOKEN_PRIVILEGES
1909GetPrivilegesToDelete(HANDLE hToken)
1914 PTOKEN_PRIVILEGES tokenPrivs;
1916 LUID luidChangeNotify;
1918 if (!LookupPrivilegeValue(NULL, SE_LOCK_MEMORY_NAME, &luidLockPages) ||
1919 !LookupPrivilegeValue(NULL, SE_CHANGE_NOTIFY_NAME, &luidChangeNotify))
1921 write_stderr(
_(
"%s: could not get LUIDs for privileges: error code %lu\n"),
1922 progname, (
unsigned long) GetLastError());
1926 if (!GetTokenInformation(hToken, TokenPrivileges, NULL, 0, &length) &&
1927 GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1929 write_stderr(
_(
"%s: could not get token information: error code %lu\n"),
1930 progname, (
unsigned long) GetLastError());
1936 if (tokenPrivs == NULL)
1942 if (!GetTokenInformation(hToken, TokenPrivileges, tokenPrivs, length, &length))
1944 write_stderr(
_(
"%s: could not get token information: error code %lu\n"),
1945 progname, (
unsigned long) GetLastError());
1950 for (
i = 0;
i < tokenPrivs->PrivilegeCount;
i++)
1952 if (memcmp(&tokenPrivs->Privileges[
i].Luid, &luidLockPages,
sizeof(LUID)) == 0 ||
1953 memcmp(&tokenPrivs->Privileges[
i].Luid, &luidChangeNotify,
sizeof(LUID)) == 0)
1955 for (
j =
i;
j < tokenPrivs->PrivilegeCount - 1;
j++)
1956 tokenPrivs->Privileges[
j] = tokenPrivs->Privileges[
j + 1];
1957 tokenPrivs->PrivilegeCount--;
1976 printf(
_(
"%s is a utility to initialize, start, stop, or control a PostgreSQL server.\n\n"),
progname);
1979 printf(
_(
" %s start [-D DATADIR] [-l FILENAME] [-W] [-t SECS] [-s]\n"
1980 " [-o OPTIONS] [-p PATH] [-c]\n"),
progname);
1981 printf(
_(
" %s stop [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s]\n"),
progname);
1982 printf(
_(
" %s restart [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s]\n"
1983 " [-o OPTIONS] [-c]\n"),
progname);
1986 printf(
_(
" %s promote [-D DATADIR] [-W] [-t SECS] [-s]\n"),
progname);
1990 printf(
_(
" %s register [-D DATADIR] [-N SERVICENAME] [-U USERNAME] [-P PASSWORD]\n"
1991 " [-S START-TYPE] [-e SOURCE] [-W] [-t SECS] [-s] [-o OPTIONS]\n"),
progname);
1995 printf(
_(
"\nCommon options:\n"));
1996 printf(
_(
" -D, --pgdata=DATADIR location of the database storage area\n"));
1998 printf(
_(
" -e SOURCE event source for logging when running as a service\n"));
2000 printf(
_(
" -s, --silent only print errors, no informational messages\n"));
2001 printf(
_(
" -t, --timeout=SECS seconds to wait when using -w option\n"));
2002 printf(
_(
" -V, --version output version information, then exit\n"));
2003 printf(
_(
" -w, --wait wait until operation completes (default)\n"));
2004 printf(
_(
" -W, --no-wait do not wait until operation completes\n"));
2005 printf(
_(
" -?, --help show this help, then exit\n"));
2006 printf(
_(
"If the -D option is omitted, the environment variable PGDATA is used.\n"));
2008 printf(
_(
"\nOptions for start or restart:\n"));
2009#if defined(HAVE_GETRLIMIT)
2010 printf(
_(
" -c, --core-files allow postgres to produce core files\n"));
2012 printf(
_(
" -c, --core-files not applicable on this platform\n"));
2014 printf(
_(
" -l, --log=FILENAME write (or append) server log to FILENAME\n"));
2015 printf(
_(
" -o, --options=OPTIONS command line options to pass to postgres\n"
2016 " (PostgreSQL server executable) or initdb\n"));
2017 printf(
_(
" -p PATH-TO-POSTGRES normally not necessary\n"));
2018 printf(
_(
"\nOptions for stop or restart:\n"));
2019 printf(
_(
" -m, --mode=MODE MODE can be \"smart\", \"fast\", or \"immediate\"\n"));
2021 printf(
_(
"\nShutdown modes are:\n"));
2022 printf(
_(
" smart quit after all clients have disconnected\n"));
2023 printf(
_(
" fast quit directly, with proper shutdown (default)\n"));
2024 printf(
_(
" immediate quit without complete shutdown; will lead to recovery on restart\n"));
2026 printf(
_(
"\nAllowed signal names for kill:\n"));
2027 printf(
" ABRT HUP INT KILL QUIT TERM USR1 USR2\n");
2030 printf(
_(
"\nOptions for register and unregister:\n"));
2031 printf(
_(
" -N SERVICENAME service name with which to register PostgreSQL server\n"));
2032 printf(
_(
" -P PASSWORD password of account to register PostgreSQL server\n"));
2033 printf(
_(
" -U USERNAME user name of account to register PostgreSQL server\n"));
2034 printf(
_(
" -S START-TYPE service start type to register PostgreSQL server\n"));
2036 printf(
_(
"\nStart types are:\n"));
2037 printf(
_(
" auto start service automatically during system startup (default)\n"));
2038 printf(
_(
" demand start service on demand\n"));
2041 printf(
_(
"\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
2042 printf(
_(
"%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
2050 if (strcmp(modeopt,
"s") == 0 || strcmp(modeopt,
"smart") == 0)
2055 else if (strcmp(modeopt,
"f") == 0 || strcmp(modeopt,
"fast") == 0)
2060 else if (strcmp(modeopt,
"i") == 0 || strcmp(modeopt,
"immediate") == 0)
2078 if (strcmp(signame,
"HUP") == 0)
2080 else if (strcmp(signame,
"INT") == 0)
2082 else if (strcmp(signame,
"QUIT") == 0)
2084 else if (strcmp(signame,
"ABRT") == 0)
2086 else if (strcmp(signame,
"KILL") == 0)
2088 else if (strcmp(signame,
"TERM") == 0)
2090 else if (strcmp(signame,
"USR1") == 0)
2092 else if (strcmp(signame,
"USR2") == 0)
2105set_starttype(
char *starttypeopt)
2107 if (strcmp(starttypeopt,
"a") == 0 || strcmp(starttypeopt,
"auto") == 0)
2108 pgctl_start_type = SERVICE_AUTO_START;
2109 else if (strcmp(starttypeopt,
"d") == 0 || strcmp(starttypeopt,
"demand") == 0)
2110 pgctl_start_type = SERVICE_DEMAND_START;
2160 cmd =
psprintf(
"\"%s\" -C data_directory %s%s",
2166 fd = popen(cmd,
"r");
2169 write_stderr(
_(
"%s: could not determine the data directory using command \"%s\"\n"),
progname, cmd);
2196 ret = control_file_data->
state;
2197 pfree(control_file_data);
2205 static struct option long_options[] = {
2242 if (strcmp(argv[1],
"--help") == 0 || strcmp(argv[1],
"-?") == 0)
2247 else if (strcmp(argv[1],
"--version") == 0 || strcmp(argv[1],
"-V") == 0)
2249 puts(
"pg_ctl (PostgreSQL) " PG_VERSION);
2261 "Please log in (using, e.g., \"su\") as the "
2262 "(unprivileged) user that will\n"
2263 "own the server process.\n"),
2269 env_wait = getenv(
"PGCTLTIMEOUT");
2270 if (env_wait != NULL)
2274 while ((
c =
getopt_long(argc, argv,
"cD:e:l:m:N:o:p:P:sS:t:U:wW",
2275 long_options, &option_index)) != -1)
2285 setenv(
"PGDATA", pgdata_D, 1);
2316 free(old_post_opts);
2332 write_stderr(
_(
"%s: -S option not supported on this platform\n"),
2342 if (strchr(
optarg,
'\\'))
2367 if (strcmp(argv[
optind],
"init") == 0
2368 || strcmp(argv[
optind],
"initdb") == 0)
2370 else if (strcmp(argv[
optind],
"start") == 0)
2372 else if (strcmp(argv[
optind],
"stop") == 0)
2374 else if (strcmp(argv[
optind],
"restart") == 0)
2376 else if (strcmp(argv[
optind],
"reload") == 0)
2378 else if (strcmp(argv[
optind],
"status") == 0)
2380 else if (strcmp(argv[
optind],
"promote") == 0)
2382 else if (strcmp(argv[
optind],
"logrotate") == 0)
2384 else if (strcmp(argv[
optind],
"kill") == 0)
2394 killproc = atol(argv[++
optind]);
2397 else if (strcmp(argv[
optind],
"register") == 0)
2399 else if (strcmp(argv[
optind],
"unregister") == 0)
2401 else if (strcmp(argv[
optind],
"runservice") == 0)
2443 write_stderr(
_(
"%s: no database directory specified and environment variable PGDATA unset\n"),
2503 pgwin32_doRegister();
2506 pgwin32_doUnregister();
2509 pgwin32_doRunAsService();
#define PG_TEXTDOMAIN(domain)
#define pg_attribute_printf(f, a)
int find_my_exec(const char *argv0, char *retpath)
void set_pglocale_pgservice(const char *argv0, const char *app)
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
ControlFileData * get_controlfile(const char *DataDir, bool *crc_ok_p)
void * pg_malloc(size_t size)
void * pg_malloc_extended(size_t size, int flags)
char * pg_strdup(const char *in)
#define MCXT_ALLOC_NO_OOM
bool GetDataDirectoryCreatePerm(const char *dataDir)
#define PG_MODE_MASK_OWNER
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
#define required_argument
char my_exec_path[MAXPGPATH]
void pg_logging_init(const char *argv0)
void pfree(void *pointer)
#define DEFAULT_EVENT_SOURCE
@ DB_SHUTDOWNED_IN_RECOVERY
static void read_post_opts(void)
static void static void do_advice(void)
static void do_reload(void)
static WaitPMResult wait_for_postmaster_start(pid_t pm_pid, bool do_checkpoint)
static void do_help(void)
static void free_readfile(char **optlines)
static char * register_username
static char * event_source
static void trap_sigint_during_startup(SIGNAL_ARGS)
static volatile pid_t postmasterPID
static void adjust_data_dir(void)
static char * register_servicename
static char version_file[MAXPGPATH]
static pid_t get_pgpid(bool is_status_request)
static bool allow_core_files
static char * find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
int main(int argc, char **argv)
static char ** readfile(const char *path, int *numlines)
static bool wait_for_postmaster_promote(void)
static char postopts_file[MAXPGPATH]
static void unlimit_core_size(void)
@ POSTMASTER_SHUTDOWN_IN_RECOVERY
@ POSTMASTER_STILL_STARTING
static void set_mode(char *modeopt)
static char promote_file[MAXPGPATH]
StaticAssertDecl(USECS_PER_SEC % WAITS_PER_SEC==0, "WAITS_PER_SEC must divide USECS_PER_SEC evenly")
static void do_start(void)
static DBState get_control_dbstate(void)
static void do_logrotate(void)
static void do_stop(void)
static char pid_file[MAXPGPATH]
static char * register_password
static CtlCommand ctl_command
static void do_init(void)
static void print_msg(const char *msg)
static bool postmaster_is_alive(pid_t pid)
static pid_t start_postmaster(void)
static void do_restart(void)
static bool wait_seconds_arg
static bool wait_for_postmaster_stop(void)
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
static void do_promote(void)
static void set_sig(char *signame)
static const char * progname
static void do_status(void)
static char logrotate_file[MAXPGPATH]
static void do_kill(pid_t pid)
static ShutdownMode shutdown_mode
PGDLLIMPORT char * optarg
#define PM_STATUS_STANDBY
#define LOCK_FILE_LINE_START_TIME
#define LOCK_FILE_LINE_PM_STATUS
#define LOCK_FILE_LINE_PID
int pg_strcasecmp(const char *s1, const char *s2)
void canonicalize_path(char *path)
void make_native_path(char *filename)
#define PG_BACKEND_VERSIONSTR
char * make_absolute_path(const char *path)
const char * get_progname(const char *argv0)
size_t strlcpy(char *dst, const char *src, size_t siz)
PQExpBuffer createPQExpBuffer(void)
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
static int fd(const char *x, int i)
char * psprintf(const char *fmt,...)
void pg_usleep(long microsec)
int pg_strip_crlf(char *str)
BOOL AddUserToTokenDacl(HANDLE hToken)
int pgwin32_is_service(void)