1 /*-------------------------------------------------------------------------
3 * pg_ctl --- start/stops/restarts the PostgreSQL server
5 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * src/bin/pg_ctl/pg_ctl.c
9 *-------------------------------------------------------------------------
14 * Need this to get defines for restricted tokens and jobs. And it
15 * has to be set before any header from the Win32 API is loaded.
17 #define _WIN32_WINNT 0x0501
20 #include "postgres_fe.h"
26 #include <sys/types.h>
30 #ifdef HAVE_SYS_RESOURCE_H
32 #include <sys/resource.h>
35 #include "libpq/pqsignal.h"
36 #include "getopt_long.h"
37 #include "miscadmin.h"
39 #if defined(__CYGWIN__)
40 #include <sys/cygwin.h>
42 /* Cygwin defines WIN32 in windows.h, but we don't want it. */
46 /* PID can be negative for standalone backend */
71 RUN_AS_SERVICE_COMMAND
74 #define DEFAULT_WAIT 60
76 static bool do_wait = false;
77 static bool wait_set = false;
78 static int wait_seconds = DEFAULT_WAIT;
79 static bool silent_mode = false;
80 static ShutdownMode shutdown_mode = SMART_MODE;
81 static int sig = SIGTERM; /* default */
82 static CtlCommand ctl_command = NO_COMMAND;
83 static char *pg_data = NULL;
84 static char *pg_config = NULL;
85 static char *pgdata_opt = NULL;
86 static char *post_opts = NULL;
87 static const char *progname;
88 static char *log_file = NULL;
89 static char *exec_path = NULL;
90 static char *register_servicename = "PostgreSQL"; /* FIXME: + version ID? */
91 static char *register_username = NULL;
92 static char *register_password = NULL;
93 static char *argv0 = NULL;
94 static bool allow_core_files = false;
95 static time_t start_time;
97 static char postopts_file[MAXPGPATH];
98 static char pid_file[MAXPGPATH];
99 static char backup_file[MAXPGPATH];
100 static char recovery_file[MAXPGPATH];
101 static char promote_file[MAXPGPATH];
103 #if defined(WIN32) || defined(__CYGWIN__)
104 static DWORD pgctl_start_type = SERVICE_AUTO_START;
105 static SERVICE_STATUS status;
106 static SERVICE_STATUS_HANDLE hStatus = (SERVICE_STATUS_HANDLE) 0;
107 static HANDLE shutdownHandles[2];
108 static pid_t postmasterPID = -1;
110 #define shutdownEvent shutdownHandles[0]
111 #define postmasterProcess shutdownHandles[1]
116 write_stderr(const char *fmt,...)
117 /* This extension allows gcc to check the format string for consistency with
118 the supplied arguments. */
119 __attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2)));
120 static void *pg_malloc(size_t size);
121 static char *xstrdup(const char *s);
122 static void do_advice(void);
123 static void do_help(void);
124 static void set_mode(char *modeopt);
125 static void set_sig(char *signame);
126 static void do_init(void);
127 static void do_start(void);
128 static void do_stop(void);
129 static void do_restart(void);
130 static void do_reload(void);
131 static void do_status(void);
132 static void do_promote(void);
133 static void do_kill(pgpid_t pid);
134 static void print_msg(const char *msg);
135 static void adjust_data_dir(void);
137 #if defined(WIN32) || defined(__CYGWIN__)
138 static bool pgwin32_IsInstalled(SC_HANDLE);
139 static char *pgwin32_CommandLine(bool);
140 static void pgwin32_doRegister(void);
141 static void pgwin32_doUnregister(void);
142 static void pgwin32_SetServiceStatus(DWORD);
143 static void WINAPI pgwin32_ServiceHandler(DWORD);
144 static void WINAPI pgwin32_ServiceMain(DWORD, LPTSTR *);
145 static void pgwin32_doRunAsService(void);
146 static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service);
149 static pgpid_t get_pgpid(void);
150 static char **readfile(const char *path);
151 static int start_postmaster(void);
152 static void read_post_opts(void);
154 static PGPing test_postmaster_connection(bool);
155 static bool postmaster_is_alive(pid_t pid);
157 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
158 static void unlimit_core_size(void);
162 #if defined(WIN32) || defined(__CYGWIN__)
164 write_eventlog(int level, const char *line)
166 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
168 if (silent_mode && level == EVENTLOG_INFORMATION_TYPE)
171 if (evtHandle == INVALID_HANDLE_VALUE)
173 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
174 if (evtHandle == NULL)
176 evtHandle = INVALID_HANDLE_VALUE;
181 ReportEvent(evtHandle,
184 0, /* All events are Id 0 */
194 * Write errors to stderr (or by equal means when stderr is
198 write_stderr(const char *fmt,...)
203 #if !defined(WIN32) && !defined(__CYGWIN__)
204 /* On Unix, we just fprintf to stderr */
205 vfprintf(stderr, fmt, ap);
209 * On Win32, we print to stderr if running on a console, or write to
210 * eventlog if running as a service
212 if (!isatty(fileno(stderr))) /* Running as a service */
214 char errbuf[2048]; /* Arbitrary size? */
216 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
218 write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
221 /* Not running as service, write to stderr */
222 vfprintf(stderr, fmt, ap);
228 * routines to check memory allocations and fail noisily.
232 pg_malloc(size_t size)
236 result = malloc(size);
239 write_stderr(_("%s: out of memory\n"), progname);
247 xstrdup(const char *s)
254 write_stderr(_("%s: out of memory\n"), progname);
261 * Given an already-localized string, print it to stdout unless the
262 * user has specified that no messages should be printed.
265 print_msg(const char *msg)
280 pidf = fopen(pid_file, "r");
283 /* No pid file, not an error on startup */
288 write_stderr(_("%s: could not open PID file \"%s\": %s\n"),
289 progname, pid_file, strerror(errno));
293 if (fscanf(pidf, "%ld", &pid) != 1)
295 write_stderr(_("%s: invalid data in PID file \"%s\"\n"),
300 return (pgpid_t) pid;
305 * get the lines from a text file - return NULL if file can't be opened
308 readfile(const char *path)
318 if ((infile = fopen(path, "r")) == NULL)
321 /* pass over the file twice - the first time to size the result */
323 while ((c = fgetc(infile)) != EOF)
329 if (linelen > maxlength)
335 /* handle last line without a terminating newline (yuck) */
338 if (linelen > maxlength)
341 /* set up the result and the line buffer */
342 result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
343 buffer = (char *) pg_malloc(maxlength + 1);
345 /* now reprocess the file and store the lines */
348 while (fgets(buffer, maxlength + 1, infile) != NULL)
349 result[nlines++] = xstrdup(buffer);
353 result[nlines] = NULL;
361 * start/test/stop routines
365 start_postmaster(void)
372 * Since there might be quotes to handle here, it is easier simply to pass
373 * everything to a shell to process them.
375 * XXX it would be better to fork and exec so that we would know the child
376 * postmaster's PID directly; then test_postmaster_connection could use
377 * the PID without having to rely on reading it back from the pidfile.
379 if (log_file != NULL)
380 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1 &" SYSTEMQUOTE,
381 exec_path, pgdata_opt, post_opts,
384 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s < \"%s\" 2>&1 &" SYSTEMQUOTE,
385 exec_path, pgdata_opt, post_opts, DEVNULL);
391 * On win32 we don't use system(). So we don't need to use & (which would
392 * be START /B on win32). However, we still call the shell (CMD.EXE) with
393 * it to handle redirection etc.
395 PROCESS_INFORMATION pi;
397 if (log_file != NULL)
398 snprintf(cmd, MAXPGPATH, "CMD /C " SYSTEMQUOTE "\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1" SYSTEMQUOTE,
399 exec_path, pgdata_opt, post_opts, DEVNULL, log_file);
401 snprintf(cmd, MAXPGPATH, "CMD /C " SYSTEMQUOTE "\"%s\" %s%s < \"%s\" 2>&1" SYSTEMQUOTE,
402 exec_path, pgdata_opt, post_opts, DEVNULL);
404 if (!CreateRestrictedProcess(cmd, &pi, false))
405 return GetLastError();
406 CloseHandle(pi.hProcess);
407 CloseHandle(pi.hThread);
415 * Find the pgport and try a connection
417 * Note that the checkpoint parameter enables a Windows service control
418 * manager checkpoint, it's got nothing to do with database checkpoints!!
421 test_postmaster_connection(bool do_checkpoint)
423 PGPing ret = PQPING_NO_RESPONSE;
424 bool found_stale_pidfile = false;
426 char connstr[MAXPGPATH * 2 + 256];
429 /* if requested wait time is zero, return "still starting up" code */
430 if (wait_seconds <= 0)
431 return PQPING_REJECT;
435 for (i = 0; i < wait_seconds; i++)
437 /* Do we need a connection string? */
438 if (connstr[0] == '\0')
441 * The number of lines in postmaster.pid tells us several things:
444 * 0 lock file created but status not written
445 * 2 pre-9.1 server, shared memory not created
446 * 3 pre-9.1 server, shared memory created
447 * 5 9.1+ server, ports not opened
448 * 6 9.1+ server, shared memory not created
449 * 7 9.1+ server, shared memory created
451 * This code does not support pre-9.1 servers. On Unix machines
452 * we could consider extracting the port number from the shmem
453 * key, but that (a) is not robust, and (b) doesn't help with
454 * finding out the socket directory. And it wouldn't work anyway
457 * If we see less than 6 lines in postmaster.pid, just keep
463 /* Try to read the postmaster.pid file */
464 if ((optlines = readfile(pid_file)) != NULL &&
465 optlines[0] != NULL &&
466 optlines[1] != NULL &&
469 if (optlines[3] == NULL)
471 /* File is exactly three lines, must be pre-9.1 */
472 write_stderr(_("\n%s: -w option is not supported when starting a pre-9.1 server\n"),
474 return PQPING_NO_ATTEMPT;
476 else if (optlines[4] != NULL &&
479 /* File is complete enough for us, parse it */
484 * Make sanity checks. If it's for a standalone backend
485 * (negative PID), or the recorded start time is before
486 * pg_ctl started, then either we are looking at the wrong
487 * data directory, or this is a pre-existing pidfile that
488 * hasn't (yet?) been overwritten by our child postmaster.
489 * Allow 2 seconds slop for possible cross-process clock
492 pmpid = atol(optlines[LOCK_FILE_LINE_PID - 1]);
493 pmstart = atol(optlines[LOCK_FILE_LINE_START_TIME - 1]);
494 if (pmpid <= 0 || pmstart < start_time - 2)
497 * Set flag to report stale pidfile if it doesn't get
498 * overwritten before we give up waiting.
500 found_stale_pidfile = true;
505 * OK, seems to be a valid pidfile from our child.
510 char host_str[MAXPGPATH];
512 found_stale_pidfile = false;
513 pm_pid = (pgpid_t) pmpid;
516 * Extract port number and host string to use. Prefer
517 * using Unix socket if available.
519 portnum = atoi(optlines[LOCK_FILE_LINE_PORT - 1]);
520 sockdir = optlines[LOCK_FILE_LINE_SOCKET_DIR - 1];
521 hostaddr = optlines[LOCK_FILE_LINE_LISTEN_ADDR - 1];
524 * While unix_socket_directory can accept relative
525 * directories, libpq's host parameter must have a
526 * leading slash to indicate a socket directory. So,
527 * ignore sockdir if it's relative, and try to use TCP
530 if (sockdir[0] == '/')
531 strlcpy(host_str, sockdir, sizeof(host_str));
533 strlcpy(host_str, hostaddr, sizeof(host_str));
535 /* remove trailing newline */
536 if (strchr(host_str, '\n') != NULL)
537 *strchr(host_str, '\n') = '\0';
539 /* Fail if couldn't get either sockdir or host addr */
540 if (host_str[0] == '\0')
542 write_stderr(_("\n%s: -w option cannot use a relative socket directory specification\n"),
544 return PQPING_NO_ATTEMPT;
547 /* If postmaster is listening on "*", use localhost */
548 if (strcmp(host_str, "*") == 0)
549 strcpy(host_str, "localhost");
552 * We need to set connect_timeout otherwise on Windows
553 * the Service Control Manager (SCM) will probably
556 snprintf(connstr, sizeof(connstr),
557 "dbname=postgres port=%d host='%s' connect_timeout=5",
564 /* If we have a connection string, ping the server */
565 if (connstr[0] != '\0')
567 ret = PQping(connstr);
568 if (ret == PQPING_OK || ret == PQPING_NO_ATTEMPT)
573 * The postmaster should create postmaster.pid very soon after being
574 * started. If it's not there after we've waited 5 or more seconds,
575 * assume startup failed and give up waiting. (Note this covers both
576 * cases where the pidfile was never created, and where it was created
577 * and then removed during postmaster exit.) Also, if there *is* a
578 * file there but it appears stale, issue a suitable warning and give
585 if (stat(pid_file, &statbuf) != 0)
586 return PQPING_NO_RESPONSE;
588 if (found_stale_pidfile)
590 write_stderr(_("\n%s: this data directory appears to be running a pre-existing postmaster\n"),
592 return PQPING_NO_RESPONSE;
597 * If we've been able to identify the child postmaster's PID, check
598 * the process is still alive. This covers cases where the postmaster
599 * successfully created the pidfile but then crashed without removing
602 if (pm_pid > 0 && !postmaster_is_alive((pid_t) pm_pid))
603 return PQPING_NO_RESPONSE;
605 /* No response, or startup still in process; wait */
610 * Increment the wait hint by 6 secs (connection timeout + sleep)
611 * We must do this to indicate to the SCM that our startup time is
612 * changing, otherwise it'll usually send a stop signal after 20
613 * seconds, despite incrementing the checkpoint counter.
615 status.dwWaitHint += 6000;
616 status.dwCheckPoint++;
617 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
623 pg_usleep(1000000); /* 1 sec */
626 /* return result of last call to PQping */
631 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
633 unlimit_core_size(void)
637 getrlimit(RLIMIT_CORE, &lim);
638 if (lim.rlim_max == 0)
640 write_stderr(_("%s: cannot set core file size limit; disallowed by hard limit\n"),
644 else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
646 lim.rlim_cur = lim.rlim_max;
647 setrlimit(RLIMIT_CORE, &lim);
655 if (post_opts == NULL)
657 post_opts = ""; /* default */
658 if (ctl_command == RESTART_COMMAND)
662 optlines = readfile(postopts_file);
663 if (optlines == NULL)
665 write_stderr(_("%s: could not read file \"%s\"\n"), progname, postopts_file);
668 else if (optlines[0] == NULL || optlines[1] != NULL)
670 write_stderr(_("%s: option file \"%s\" must have exactly one line\n"),
671 progname, postopts_file);
680 optline = optlines[0];
681 /* trim off line endings */
682 len = strcspn(optline, "\r\n");
686 * Are we at the first option, as defined by space and
689 if ((arg1 = strstr(optline, " \"")) != NULL)
691 *arg1 = '\0'; /* terminate so we get only program
693 post_opts = arg1 + 1; /* point past whitespace */
695 if (exec_path == NULL)
703 find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
708 found_path = pg_malloc(MAXPGPATH);
710 if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
712 char full_path[MAXPGPATH];
714 if (find_my_exec(argv0, full_path) < 0)
715 strlcpy(full_path, progname, sizeof(full_path));
718 write_stderr(_("The program \"%s\" is needed by %s "
719 "but was not found in the\n"
720 "same directory as \"%s\".\n"
721 "Check your installation.\n"),
722 target, progname, full_path);
724 write_stderr(_("The program \"%s\" was found by \"%s\"\n"
725 "but was not the same version as %s.\n"
726 "Check your installation.\n"),
727 target, full_path, progname);
739 if (exec_path == NULL)
740 exec_path = find_other_exec_or_die(argv0, "initdb", "initdb (PostgreSQL) " PG_VERSION "\n");
742 if (pgdata_opt == NULL)
745 if (post_opts == NULL)
749 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s" SYSTEMQUOTE,
750 exec_path, pgdata_opt, post_opts);
752 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s > \"%s\"" SYSTEMQUOTE,
753 exec_path, pgdata_opt, post_opts, DEVNULL);
755 if (system(cmd) != 0)
757 write_stderr(_("%s: database system initialization failed\n"), progname);
768 if (ctl_command != RESTART_COMMAND)
770 old_pid = get_pgpid();
772 write_stderr(_("%s: another server might be running; "
773 "trying to start server anyway\n"),
779 /* No -D or -D already added during server start */
780 if (ctl_command == RESTART_COMMAND || pgdata_opt == NULL)
783 if (exec_path == NULL)
784 exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
786 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
787 if (allow_core_files)
792 * If possible, tell the postmaster our parent shell's PID (see the
793 * comments in CreateLockFile() for motivation). Windows hasn't got
794 * getppid() unfortunately.
798 static char env_var[32];
800 snprintf(env_var, sizeof(env_var), "PG_GRANDPARENT_PID=%d",
806 exitcode = start_postmaster();
809 write_stderr(_("%s: could not start server: exit code was %d\n"),
816 print_msg(_("waiting for server to start..."));
818 switch (test_postmaster_connection(false))
821 print_msg(_(" done\n"));
822 print_msg(_("server started\n"));
825 print_msg(_(" stopped waiting\n"));
826 print_msg(_("server is still starting up\n"));
828 case PQPING_NO_RESPONSE:
829 print_msg(_(" stopped waiting\n"));
830 write_stderr(_("%s: could not start server\n"
831 "Examine the log output.\n"),
835 case PQPING_NO_ATTEMPT:
836 print_msg(_(" failed\n"));
837 write_stderr(_("%s: could not wait for server because of misconfiguration\n"),
843 print_msg(_("server starting\n"));
856 if (pid == 0) /* no pid file */
858 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
859 write_stderr(_("Is server running?\n"));
862 else if (pid < 0) /* standalone backend, not postmaster */
865 write_stderr(_("%s: cannot stop server; "
866 "single-user server is running (PID: %ld)\n"),
871 if (kill((pid_t) pid, sig) != 0)
873 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
880 print_msg(_("server shutting down\n"));
886 * If backup_label exists, an online backup is running. Warn the user
887 * that smart shutdown will wait for it to finish. However, if
888 * recovery.conf is also present, we're recovering from an online
889 * backup instead of performing one.
891 if (shutdown_mode == SMART_MODE &&
892 stat(backup_file, &statbuf) == 0 &&
893 stat(recovery_file, &statbuf) != 0)
895 print_msg(_("WARNING: online backup mode is active\n"
896 "Shutdown will not complete until pg_stop_backup() is called.\n\n"));
899 print_msg(_("waiting for server to shut down..."));
901 for (cnt = 0; cnt < wait_seconds; cnt++)
903 if ((pid = get_pgpid()) != 0)
906 pg_usleep(1000000); /* 1 sec */
912 if (pid != 0) /* pid file still exists */
914 print_msg(_(" failed\n"));
916 write_stderr(_("%s: server does not shut down\n"), progname);
917 if (shutdown_mode == SMART_MODE)
918 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
919 "waiting for session-initiated disconnection.\n"));
922 print_msg(_(" done\n"));
924 print_msg(_("server stopped\n"));
930 * restart/reload routines
942 if (pid == 0) /* no pid file */
944 write_stderr(_("%s: PID file \"%s\" does not exist\n"),
946 write_stderr(_("Is server running?\n"));
947 write_stderr(_("starting server anyway\n"));
951 else if (pid < 0) /* standalone backend, not postmaster */
954 if (postmaster_is_alive((pid_t) pid))
956 write_stderr(_("%s: cannot restart server; "
957 "single-user server is running (PID: %ld)\n"),
959 write_stderr(_("Please terminate the single-user server and try again.\n"));
964 if (postmaster_is_alive((pid_t) pid))
966 if (kill((pid_t) pid, sig) != 0)
968 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
974 * If backup_label exists, an online backup is running. Warn the user
975 * that smart shutdown will wait for it to finish. However, if
976 * recovery.conf is also present, we're recovering from an online
977 * backup instead of performing one.
979 if (shutdown_mode == SMART_MODE &&
980 stat(backup_file, &statbuf) == 0 &&
981 stat(recovery_file, &statbuf) != 0)
983 print_msg(_("WARNING: online backup mode is active\n"
984 "Shutdown will not complete until pg_stop_backup() is called.\n\n"));
987 print_msg(_("waiting for server to shut down..."));
989 /* always wait for restart */
991 for (cnt = 0; cnt < wait_seconds; cnt++)
993 if ((pid = get_pgpid()) != 0)
996 pg_usleep(1000000); /* 1 sec */
1002 if (pid != 0) /* pid file still exists */
1004 print_msg(_(" failed\n"));
1006 write_stderr(_("%s: server does not shut down\n"), progname);
1007 if (shutdown_mode == SMART_MODE)
1008 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1009 "waiting for session-initiated disconnection.\n"));
1013 print_msg(_(" done\n"));
1014 print_msg(_("server stopped\n"));
1018 write_stderr(_("%s: old server process (PID: %ld) seems to be gone\n"),
1020 write_stderr(_("starting server anyway\n"));
1032 if (pid == 0) /* no pid file */
1034 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1035 write_stderr(_("Is server running?\n"));
1038 else if (pid < 0) /* standalone backend, not postmaster */
1041 write_stderr(_("%s: cannot reload server; "
1042 "single-user server is running (PID: %ld)\n"),
1044 write_stderr(_("Please terminate the single-user server and try again.\n"));
1048 if (kill((pid_t) pid, sig) != 0)
1050 write_stderr(_("%s: could not send reload signal (PID: %ld): %s\n"),
1051 progname, pid, strerror(errno));
1055 print_msg(_("server signaled\n"));
1068 struct stat statbuf;
1072 if (pid == 0) /* no pid file */
1074 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1075 write_stderr(_("Is server running?\n"));
1078 else if (pid < 0) /* standalone backend, not postmaster */
1081 write_stderr(_("%s: cannot promote server; "
1082 "single-user server is running (PID: %ld)\n"),
1087 /* If recovery.conf doesn't exist, the server is not in standby mode */
1088 if (stat(recovery_file, &statbuf) != 0)
1090 write_stderr(_("%s: cannot promote server; "
1091 "server is not in standby mode\n"),
1096 if ((prmfile = fopen(promote_file, "w")) == NULL)
1098 write_stderr(_("%s: could not create promote signal file \"%s\": %s\n"),
1099 progname, promote_file, strerror(errno));
1102 if (fclose(prmfile))
1104 write_stderr(_("%s: could not write promote signal file \"%s\": %s\n"),
1105 progname, promote_file, strerror(errno));
1110 if (kill((pid_t) pid, sig) != 0)
1112 write_stderr(_("%s: could not send promote signal (PID: %ld): %s\n"),
1113 progname, pid, strerror(errno));
1114 if (unlink(promote_file) != 0)
1115 write_stderr(_("%s: could not remove promote signal file \"%s\": %s\n"),
1116 progname, promote_file, strerror(errno));
1120 print_msg(_("server promoting\n"));
1129 postmaster_is_alive(pid_t pid)
1132 * Test to see if the process is still there. Note that we do not
1133 * consider an EPERM failure to mean that the process is still there;
1134 * EPERM must mean that the given PID belongs to some other userid, and
1135 * considering the permissions on $PGDATA, that means it's not the
1136 * postmaster we are after.
1138 * Don't believe that our own PID or parent shell's PID is the postmaster,
1139 * either. (Windows hasn't got getppid(), though.)
1141 if (pid == getpid())
1144 if (pid == getppid())
1147 if (kill(pid, 0) == 0)
1158 /* Is there a pid file? */
1161 /* standalone backend? */
1165 if (postmaster_is_alive((pid_t) pid))
1167 printf(_("%s: single-user server is running (PID: %ld)\n"),
1173 /* must be a postmaster */
1175 if (postmaster_is_alive((pid_t) pid))
1179 printf(_("%s: server is running (PID: %ld)\n"),
1182 optlines = readfile(postopts_file);
1183 if (optlines != NULL)
1184 for (; *optlines != NULL; optlines++)
1185 fputs(*optlines, stdout);
1190 printf(_("%s: no server running\n"), progname);
1192 * The Linux Standard Base Core Specification 3.1 says this should return '3'
1193 * http://refspecs.freestandards.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
1201 do_kill(pgpid_t pid)
1203 if (kill((pid_t) pid, sig) != 0)
1205 write_stderr(_("%s: could not send signal %d (PID: %ld): %s\n"),
1206 progname, sig, pid, strerror(errno));
1211 #if defined(WIN32) || defined(__CYGWIN__)
1214 pgwin32_IsInstalled(SC_HANDLE hSCM)
1216 SC_HANDLE hService = OpenService(hSCM, register_servicename, SERVICE_QUERY_CONFIG);
1217 bool bResult = (hService != NULL);
1220 CloseServiceHandle(hService);
1225 pgwin32_CommandLine(bool registration)
1227 static char cmdLine[MAXPGPATH];
1231 char buf[MAXPGPATH];
1236 ret = find_my_exec(argv0, cmdLine);
1239 write_stderr(_("%s: could not find own program executable\n"), progname);
1245 ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1249 write_stderr(_("%s: could not find postgres program executable\n"), progname);
1255 /* need to convert to windows path */
1256 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
1257 cygwin_conv_path(CCP_POSIX_TO_WIN_A, cmdLine, buf, sizeof(buf));
1259 cygwin_conv_to_full_win32_path(cmdLine, buf);
1261 strcpy(cmdLine, buf);
1266 if (pg_strcasecmp(cmdLine + strlen(cmdLine) - 4, ".exe"))
1268 /* If commandline does not end in .exe, append it */
1269 strcat(cmdLine, ".exe");
1271 strcat(cmdLine, " runservice -N \"");
1272 strcat(cmdLine, register_servicename);
1273 strcat(cmdLine, "\"");
1278 strcat(cmdLine, " -D \"");
1279 strcat(cmdLine, pg_config);
1280 strcat(cmdLine, "\"");
1283 if (registration && do_wait)
1284 strcat(cmdLine, " -w");
1286 if (registration && wait_seconds != DEFAULT_WAIT)
1288 sprintf(cmdLine + strlen(cmdLine), " -t %d", wait_seconds);
1290 if (registration && silent_mode)
1291 strcat(cmdLine, " -s");
1295 strcat(cmdLine, " ");
1297 strcat(cmdLine, " -o \"");
1298 strcat(cmdLine, post_opts);
1300 strcat(cmdLine, "\"");
1307 pgwin32_doRegister(void)
1310 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1314 write_stderr(_("%s: could not open service manager\n"), progname);
1317 if (pgwin32_IsInstalled(hSCM))
1319 CloseServiceHandle(hSCM);
1320 write_stderr(_("%s: service \"%s\" already registered\n"), progname, register_servicename);
1324 if ((hService = CreateService(hSCM, register_servicename, register_servicename,
1325 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1326 pgctl_start_type, SERVICE_ERROR_NORMAL,
1327 pgwin32_CommandLine(true),
1328 NULL, NULL, "RPCSS\0", register_username, register_password)) == NULL)
1330 CloseServiceHandle(hSCM);
1331 write_stderr(_("%s: could not register service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1334 CloseServiceHandle(hService);
1335 CloseServiceHandle(hSCM);
1339 pgwin32_doUnregister(void)
1342 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1346 write_stderr(_("%s: could not open service manager\n"), progname);
1349 if (!pgwin32_IsInstalled(hSCM))
1351 CloseServiceHandle(hSCM);
1352 write_stderr(_("%s: service \"%s\" not registered\n"), progname, register_servicename);
1356 if ((hService = OpenService(hSCM, register_servicename, DELETE)) == NULL)
1358 CloseServiceHandle(hSCM);
1359 write_stderr(_("%s: could not open service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1362 if (!DeleteService(hService))
1364 CloseServiceHandle(hService);
1365 CloseServiceHandle(hSCM);
1366 write_stderr(_("%s: could not unregister service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1369 CloseServiceHandle(hService);
1370 CloseServiceHandle(hSCM);
1374 pgwin32_SetServiceStatus(DWORD currentState)
1376 status.dwCurrentState = currentState;
1377 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1381 pgwin32_ServiceHandler(DWORD request)
1385 case SERVICE_CONTROL_STOP:
1386 case SERVICE_CONTROL_SHUTDOWN:
1389 * We only need a short wait hint here as it just needs to wait
1390 * for the next checkpoint. They occur every 5 seconds during
1393 status.dwWaitHint = 10000;
1394 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1395 SetEvent(shutdownEvent);
1398 case SERVICE_CONTROL_PAUSE:
1399 /* Win32 config reloading */
1400 status.dwWaitHint = 5000;
1401 kill(postmasterPID, SIGHUP);
1404 /* FIXME: These could be used to replace other signals etc */
1405 case SERVICE_CONTROL_CONTINUE:
1406 case SERVICE_CONTROL_INTERROGATE:
1413 pgwin32_ServiceMain(DWORD argc, LPTSTR *argv)
1415 PROCESS_INFORMATION pi;
1418 /* Initialize variables */
1419 status.dwWin32ExitCode = S_OK;
1420 status.dwCheckPoint = 0;
1421 status.dwWaitHint = 60000;
1422 status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1423 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
1424 status.dwServiceSpecificExitCode = 0;
1425 status.dwCurrentState = SERVICE_START_PENDING;
1427 memset(&pi, 0, sizeof(pi));
1431 /* Register the control request handler */
1432 if ((hStatus = RegisterServiceCtrlHandler(register_servicename, pgwin32_ServiceHandler)) == (SERVICE_STATUS_HANDLE) 0)
1435 if ((shutdownEvent = CreateEvent(NULL, true, false, NULL)) == NULL)
1438 /* Start the postmaster */
1439 pgwin32_SetServiceStatus(SERVICE_START_PENDING);
1440 if (!CreateRestrictedProcess(pgwin32_CommandLine(false), &pi, true))
1442 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1445 postmasterPID = pi.dwProcessId;
1446 postmasterProcess = pi.hProcess;
1447 CloseHandle(pi.hThread);
1451 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Waiting for server startup...\n"));
1452 if (test_postmaster_connection(true) != PQPING_OK)
1454 write_eventlog(EVENTLOG_ERROR_TYPE, _("Timed out waiting for server startup\n"));
1455 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1458 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Server started and accepting connections\n"));
1461 pgwin32_SetServiceStatus(SERVICE_RUNNING);
1463 /* Wait for quit... */
1464 ret = WaitForMultipleObjects(2, shutdownHandles, FALSE, INFINITE);
1466 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1469 case WAIT_OBJECT_0: /* shutdown event */
1470 kill(postmasterPID, SIGINT);
1473 * Increment the checkpoint and try again Abort after 12
1474 * checkpoints as the postmaster has probably hung
1476 while (WaitForSingleObject(postmasterProcess, 5000) == WAIT_TIMEOUT && status.dwCheckPoint < 12)
1477 status.dwCheckPoint++;
1480 case (WAIT_OBJECT_0 + 1): /* postmaster went down */
1484 /* shouldn't get here? */
1488 CloseHandle(shutdownEvent);
1489 CloseHandle(postmasterProcess);
1491 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1495 pgwin32_doRunAsService(void)
1497 SERVICE_TABLE_ENTRY st[] = {{register_servicename, pgwin32_ServiceMain},
1500 if (StartServiceCtrlDispatcher(st) == 0)
1502 write_stderr(_("%s: could not start service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1509 * Mingw headers are incomplete, and so are the libraries. So we have to load
1510 * a whole lot of API functions dynamically. Since we have to do this anyway,
1511 * also load the couple of functions that *do* exist in minwg headers but not
1512 * on NT4. That way, we don't break on NT4.
1514 typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
1515 typedef BOOL (WINAPI * __IsProcessInJob) (HANDLE, HANDLE, PBOOL);
1516 typedef HANDLE (WINAPI * __CreateJobObject) (LPSECURITY_ATTRIBUTES, LPCTSTR);
1517 typedef BOOL (WINAPI * __SetInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD);
1518 typedef BOOL (WINAPI * __AssignProcessToJobObject) (HANDLE, HANDLE);
1519 typedef BOOL (WINAPI * __QueryInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD, LPDWORD);
1521 /* Windows API define missing from some versions of MingW headers */
1522 #ifndef DISABLE_MAX_PRIVILEGE
1523 #define DISABLE_MAX_PRIVILEGE 0x1
1527 * Create a restricted token, a job object sandbox, and execute the specified
1530 * Returns 0 on success, non-zero on failure, same as CreateProcess().
1532 * On NT4, or any other system not containing the required functions, will
1533 * launch the process under the current token without doing any modifications.
1535 * NOTE! Job object will only work when running as a service, because it's
1536 * automatically destroyed when pg_ctl exits.
1539 CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service)
1545 HANDLE restrictedToken;
1546 SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
1547 SID_AND_ATTRIBUTES dropSids[2];
1549 /* Functions loaded dynamically */
1550 __CreateRestrictedToken _CreateRestrictedToken = NULL;
1551 __IsProcessInJob _IsProcessInJob = NULL;
1552 __CreateJobObject _CreateJobObject = NULL;
1553 __SetInformationJobObject _SetInformationJobObject = NULL;
1554 __AssignProcessToJobObject _AssignProcessToJobObject = NULL;
1555 __QueryInformationJobObject _QueryInformationJobObject = NULL;
1556 HANDLE Kernel32Handle;
1557 HANDLE Advapi32Handle;
1559 ZeroMemory(&si, sizeof(si));
1562 Advapi32Handle = LoadLibrary("ADVAPI32.DLL");
1563 if (Advapi32Handle != NULL)
1565 _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken");
1568 if (_CreateRestrictedToken == NULL)
1571 * NT4 doesn't have CreateRestrictedToken, so just call ordinary
1574 write_stderr(_("%s: WARNING: cannot create restricted tokens on this platform\n"), progname);
1575 if (Advapi32Handle != NULL)
1576 FreeLibrary(Advapi32Handle);
1577 return CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, processInfo);
1580 /* Open the current token to use as a base for the restricted one */
1581 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
1583 write_stderr(_("%s: could not open process token: error code %lu\n"), progname, GetLastError());
1587 /* Allocate list of SIDs to remove */
1588 ZeroMemory(&dropSids, sizeof(dropSids));
1589 if (!AllocateAndInitializeSid(&NtAuthority, 2,
1590 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
1591 0, &dropSids[0].Sid) ||
1592 !AllocateAndInitializeSid(&NtAuthority, 2,
1593 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
1594 0, &dropSids[1].Sid))
1596 write_stderr(_("%s: could not allocate SIDs: error code %lu\n"), progname, GetLastError());
1600 b = _CreateRestrictedToken(origToken,
1601 DISABLE_MAX_PRIVILEGE,
1602 sizeof(dropSids) / sizeof(dropSids[0]),
1608 FreeSid(dropSids[1].Sid);
1609 FreeSid(dropSids[0].Sid);
1610 CloseHandle(origToken);
1611 FreeLibrary(Advapi32Handle);
1615 write_stderr(_("%s: could not create restricted token: error code %lu\n"), progname, GetLastError());
1620 AddUserToTokenDacl(restrictedToken);
1623 r = CreateProcessAsUser(restrictedToken, NULL, cmd, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, processInfo);
1625 Kernel32Handle = LoadLibrary("KERNEL32.DLL");
1626 if (Kernel32Handle != NULL)
1628 _IsProcessInJob = (__IsProcessInJob) GetProcAddress(Kernel32Handle, "IsProcessInJob");
1629 _CreateJobObject = (__CreateJobObject) GetProcAddress(Kernel32Handle, "CreateJobObjectA");
1630 _SetInformationJobObject = (__SetInformationJobObject) GetProcAddress(Kernel32Handle, "SetInformationJobObject");
1631 _AssignProcessToJobObject = (__AssignProcessToJobObject) GetProcAddress(Kernel32Handle, "AssignProcessToJobObject");
1632 _QueryInformationJobObject = (__QueryInformationJobObject) GetProcAddress(Kernel32Handle, "QueryInformationJobObject");
1635 /* Verify that we found all functions */
1636 if (_IsProcessInJob == NULL || _CreateJobObject == NULL || _SetInformationJobObject == NULL || _AssignProcessToJobObject == NULL || _QueryInformationJobObject == NULL)
1639 * IsProcessInJob() is not available on < WinXP, so there is no need
1640 * to log the error every time in that case
1644 osv.dwOSVersionInfoSize = sizeof(osv);
1645 if (!GetVersionEx(&osv) || /* could not get version */
1646 (osv.dwMajorVersion == 5 && osv.dwMinorVersion > 0) || /* 5.1=xp, 5.2=2003, etc */
1647 osv.dwMajorVersion > 5) /* anything newer should have the API */
1650 * Log error if we can't get version, or if we're on WinXP/2003 or
1653 write_stderr(_("%s: WARNING: could not locate all job object functions in system API\n"), progname);
1659 if (_IsProcessInJob(processInfo->hProcess, NULL, &inJob))
1664 * Job objects are working, and the new process isn't in one,
1665 * so we can create one safely. If any problems show up when
1666 * setting it, we're going to ignore them.
1671 sprintf(jobname, "PostgreSQL_%lu", processInfo->dwProcessId);
1673 job = _CreateJobObject(NULL, jobname);
1676 JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit;
1677 JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions;
1678 JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit;
1681 ZeroMemory(&basicLimit, sizeof(basicLimit));
1682 ZeroMemory(&uiRestrictions, sizeof(uiRestrictions));
1683 ZeroMemory(&securityLimit, sizeof(securityLimit));
1685 basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS;
1686 basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS;
1687 _SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit, sizeof(basicLimit));
1689 uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS |
1690 JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_READCLIPBOARD |
1691 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD;
1695 osv.dwOSVersionInfoSize = sizeof(osv);
1696 if (!GetVersionEx(&osv) ||
1697 osv.dwMajorVersion < 6 ||
1698 (osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0))
1701 * On Windows 7 (and presumably later),
1702 * JOB_OBJECT_UILIMIT_HANDLES prevents us from
1703 * starting as a service. So we only enable it on
1704 * Vista and earlier (version <= 6.0)
1706 uiRestrictions.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_HANDLES;
1709 _SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uiRestrictions));
1711 securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN;
1712 securityLimit.JobToken = restrictedToken;
1713 _SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit, sizeof(securityLimit));
1715 _AssignProcessToJobObject(job, processInfo->hProcess);
1722 CloseHandle(restrictedToken);
1724 ResumeThread(processInfo->hThread);
1726 FreeLibrary(Kernel32Handle);
1729 * We intentionally don't close the job object handle, because we want the
1730 * object to live on until pg_ctl shuts down.
1739 write_stderr(_("Try \"%s --help\" for more information.\n"), progname);
1747 printf(_("%s is a utility to initialize, start, stop, or control a PostgreSQL server.\n\n"), progname);
1748 printf(_("Usage:\n"));
1749 printf(_(" %s init[db] [-D DATADIR] [-s] [-o \"OPTIONS\"]\n"), progname);
1750 printf(_(" %s start [-w] [-t SECS] [-D DATADIR] [-s] [-l FILENAME] [-o \"OPTIONS\"]\n"), progname);
1751 printf(_(" %s stop [-W] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"), progname);
1752 printf(_(" %s restart [-w] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"
1753 " [-o \"OPTIONS\"]\n"), progname);
1754 printf(_(" %s reload [-D DATADIR] [-s]\n"), progname);
1755 printf(_(" %s status [-D DATADIR]\n"), progname);
1756 printf(_(" %s promote [-D DATADIR] [-s]\n"), progname);
1757 printf(_(" %s kill SIGNALNAME PID\n"), progname);
1758 #if defined(WIN32) || defined(__CYGWIN__)
1759 printf(_(" %s register [-N SERVICENAME] [-U USERNAME] [-P PASSWORD] [-D DATADIR]\n"
1760 " [-S START-TYPE] [-w] [-t SECS] [-o \"OPTIONS\"]\n"), progname);
1761 printf(_(" %s unregister [-N SERVICENAME]\n"), progname);
1764 printf(_("\nCommon options:\n"));
1765 printf(_(" -D, --pgdata DATADIR location of the database storage area\n"));
1766 printf(_(" -s, --silent only print errors, no informational messages\n"));
1767 printf(_(" -t SECS seconds to wait when using -w option\n"));
1768 printf(_(" -w wait until operation completes\n"));
1769 printf(_(" -W do not wait until operation completes\n"));
1770 printf(_(" --help show this help, then exit\n"));
1771 printf(_(" --version output version information, then exit\n"));
1772 printf(_("(The default is to wait for shutdown, but not for start or restart.)\n\n"));
1773 printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
1775 printf(_("\nOptions for start or restart:\n"));
1776 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
1777 printf(_(" -c, --core-files allow postgres to produce core files\n"));
1779 printf(_(" -c, --core-files not applicable on this platform\n"));
1781 printf(_(" -l, --log FILENAME write (or append) server log to FILENAME\n"));
1782 printf(_(" -o OPTIONS command line options to pass to postgres\n"
1783 " (PostgreSQL server executable) or initdb\n"));
1784 printf(_(" -p PATH-TO-POSTGRES normally not necessary\n"));
1785 printf(_("\nOptions for stop or restart:\n"));
1786 printf(_(" -m SHUTDOWN-MODE can be \"smart\", \"fast\", or \"immediate\"\n"));
1788 printf(_("\nShutdown modes are:\n"));
1789 printf(_(" smart quit after all clients have disconnected\n"));
1790 printf(_(" fast quit directly, with proper shutdown\n"));
1791 printf(_(" immediate quit without complete shutdown; will lead to recovery on restart\n"));
1793 printf(_("\nAllowed signal names for kill:\n"));
1794 printf(" HUP INT QUIT ABRT TERM USR1 USR2\n");
1796 #if defined(WIN32) || defined(__CYGWIN__)
1797 printf(_("\nOptions for register and unregister:\n"));
1798 printf(_(" -N SERVICENAME service name with which to register PostgreSQL server\n"));
1799 printf(_(" -P PASSWORD password of account to register PostgreSQL server\n"));
1800 printf(_(" -U USERNAME user name of account to register PostgreSQL server\n"));
1801 printf(_(" -S START-TYPE service start type to register PostgreSQL server\n"));
1803 printf(_("\nStart types are:\n"));
1804 printf(_(" auto start service automatically during system startup (default)\n"));
1805 printf(_(" demand start service on demand\n"));
1808 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
1814 set_mode(char *modeopt)
1816 if (strcmp(modeopt, "s") == 0 || strcmp(modeopt, "smart") == 0)
1818 shutdown_mode = SMART_MODE;
1821 else if (strcmp(modeopt, "f") == 0 || strcmp(modeopt, "fast") == 0)
1823 shutdown_mode = FAST_MODE;
1826 else if (strcmp(modeopt, "i") == 0 || strcmp(modeopt, "immediate") == 0)
1828 shutdown_mode = IMMEDIATE_MODE;
1833 write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname, modeopt);
1842 set_sig(char *signame)
1844 if (!strcmp(signame, "HUP"))
1846 else if (!strcmp(signame, "INT"))
1848 else if (!strcmp(signame, "QUIT"))
1850 else if (!strcmp(signame, "ABRT"))
1854 * probably should NOT provide SIGKILL
1856 * else if (!strcmp(signame,"KILL")) sig = SIGKILL;
1858 else if (!strcmp(signame, "TERM"))
1860 else if (!strcmp(signame, "USR1"))
1862 else if (!strcmp(signame, "USR2"))
1866 write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname, signame);
1873 #if defined(WIN32) || defined(__CYGWIN__)
1875 set_starttype(char *starttypeopt)
1877 if (strcmp(starttypeopt, "a") == 0 || strcmp(starttypeopt, "auto") == 0)
1878 pgctl_start_type = SERVICE_AUTO_START;
1879 else if (strcmp(starttypeopt, "d") == 0 || strcmp(starttypeopt, "demand") == 0)
1880 pgctl_start_type = SERVICE_DEMAND_START;
1883 write_stderr(_("%s: unrecognized start type \"%s\"\n"), progname, starttypeopt);
1893 * If a configuration-only directory was specified, find the real data dir.
1896 adjust_data_dir(void)
1898 char cmd[MAXPGPATH], filename[MAXPGPATH], *my_exec_path;
1901 /* If there is no postgresql.conf, it can't be a config-only dir */
1902 snprintf(filename, sizeof(filename), "%s/postgresql.conf", pg_config);
1903 if ((fd = fopen(filename, "r")) == NULL)
1907 /* If PG_VERSION exists, it can't be a config-only dir */
1908 snprintf(filename, sizeof(filename), "%s/PG_VERSION", pg_config);
1909 if ((fd = fopen(filename, "r")) != NULL)
1915 /* Must be a configuration directory, so find the data directory */
1917 /* we use a private my_exec_path to avoid interfering with later uses */
1918 if (exec_path == NULL)
1919 my_exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
1921 my_exec_path = xstrdup(exec_path);
1923 snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s -C data_directory" SYSTEMQUOTE,
1924 my_exec_path, pgdata_opt ? pgdata_opt : "", post_opts ?
1927 fd = popen(cmd, "r");
1928 if (fd == NULL || fgets(filename, sizeof(filename), fd) == NULL)
1930 write_stderr(_("%s: cannot find the data directory using %s\n"), progname, my_exec_path);
1936 /* Remove trailing newline */
1937 if (strchr(filename, '\n') != NULL)
1938 *strchr(filename, '\n') = '\0';
1941 pg_data = xstrdup(filename);
1942 canonicalize_path(pg_data);
1947 main(int argc, char **argv)
1949 static struct option long_options[] = {
1950 {"help", no_argument, NULL, '?'},
1951 {"version", no_argument, NULL, 'V'},
1952 {"log", required_argument, NULL, 'l'},
1953 {"mode", required_argument, NULL, 'm'},
1954 {"pgdata", required_argument, NULL, 'D'},
1955 {"silent", no_argument, NULL, 's'},
1956 {"timeout", required_argument, NULL, 't'},
1957 {"core-files", no_argument, NULL, 'c'},
1963 pgpid_t killproc = 0;
1965 #if defined(WIN32) || defined(__CYGWIN__)
1966 setvbuf(stderr, NULL, _IONBF, 0);
1969 progname = get_progname(argv[0]);
1970 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_ctl"));
1971 start_time = time(NULL);
1974 * save argv[0] so do_start() can look for the postmaster if necessary. we
1975 * don't look for postmaster here because in many cases we won't need it.
1979 umask(S_IRWXG | S_IRWXO);
1981 /* support --help and --version even if invoked as root */
1984 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0 ||
1985 strcmp(argv[1], "-?") == 0)
1990 else if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0)
1992 puts("pg_ctl (PostgreSQL) " PG_VERSION);
1998 * Disallow running as root, to forestall any possible security holes.
2003 write_stderr(_("%s: cannot be run as root\n"
2004 "Please log in (using, e.g., \"su\") as the "
2005 "(unprivileged) user that will\n"
2006 "own the server process.\n"),
2013 * 'Action' can be before or after args so loop over both. Some
2014 * getopt_long() implementations will reorder argv[] to place all flags
2015 * first (GNU?), but we don't rely on it. Our /port version doesn't do
2020 /* process command-line options */
2021 while (optind < argc)
2023 while ((c = getopt_long(argc, argv, "cD:l:m:N:o:p:P:sS:t:U:wW", long_options, &option_index)) != -1)
2030 char *env_var = pg_malloc(strlen(optarg) + 8);
2032 pgdata_D = xstrdup(optarg);
2033 canonicalize_path(pgdata_D);
2034 snprintf(env_var, strlen(optarg) + 8, "PGDATA=%s",
2039 * We could pass PGDATA just in an environment
2040 * variable but we do -D too for clearer postmaster
2043 pgdata_opt = pg_malloc(strlen(pgdata_D) + 7);
2044 snprintf(pgdata_opt, strlen(pgdata_D) + 7,
2050 log_file = xstrdup(optarg);
2056 register_servicename = xstrdup(optarg);
2059 post_opts = xstrdup(optarg);
2062 exec_path = xstrdup(optarg);
2065 register_password = xstrdup(optarg);
2071 #if defined(WIN32) || defined(__CYGWIN__)
2072 set_starttype(optarg);
2074 write_stderr(_("%s: -S option not supported on this platform\n"),
2080 wait_seconds = atoi(optarg);
2083 if (strchr(optarg, '\\'))
2084 register_username = xstrdup(optarg);
2086 /* Prepend .\ for local accounts */
2088 register_username = malloc(strlen(optarg) + 3);
2089 if (!register_username)
2091 write_stderr(_("%s: out of memory\n"), progname);
2094 strcpy(register_username, ".\\");
2095 strcat(register_username, optarg);
2107 allow_core_files = true;
2110 /* getopt_long already issued a suitable error message */
2116 /* Process an action */
2119 if (ctl_command != NO_COMMAND)
2121 write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
2126 if (strcmp(argv[optind], "init") == 0
2127 || strcmp(argv[optind], "initdb") == 0)
2128 ctl_command = INIT_COMMAND;
2129 else if (strcmp(argv[optind], "start") == 0)
2130 ctl_command = START_COMMAND;
2131 else if (strcmp(argv[optind], "stop") == 0)
2132 ctl_command = STOP_COMMAND;
2133 else if (strcmp(argv[optind], "restart") == 0)
2134 ctl_command = RESTART_COMMAND;
2135 else if (strcmp(argv[optind], "reload") == 0)
2136 ctl_command = RELOAD_COMMAND;
2137 else if (strcmp(argv[optind], "status") == 0)
2138 ctl_command = STATUS_COMMAND;
2139 else if (strcmp(argv[optind], "promote") == 0)
2140 ctl_command = PROMOTE_COMMAND;
2141 else if (strcmp(argv[optind], "kill") == 0)
2143 if (argc - optind < 3)
2145 write_stderr(_("%s: missing arguments for kill mode\n"), progname);
2149 ctl_command = KILL_COMMAND;
2150 set_sig(argv[++optind]);
2151 killproc = atol(argv[++optind]);
2153 #if defined(WIN32) || defined(__CYGWIN__)
2154 else if (strcmp(argv[optind], "register") == 0)
2155 ctl_command = REGISTER_COMMAND;
2156 else if (strcmp(argv[optind], "unregister") == 0)
2157 ctl_command = UNREGISTER_COMMAND;
2158 else if (strcmp(argv[optind], "runservice") == 0)
2159 ctl_command = RUN_AS_SERVICE_COMMAND;
2163 write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
2171 if (ctl_command == NO_COMMAND)
2173 write_stderr(_("%s: no operation specified\n"), progname);
2178 /* Note we put any -D switch into the env var above */
2179 pg_config = getenv("PGDATA");
2182 pg_config = xstrdup(pg_config);
2183 canonicalize_path(pg_config);
2184 pg_data = xstrdup(pg_config);
2189 if (pg_config == NULL &&
2190 ctl_command != KILL_COMMAND && ctl_command != UNREGISTER_COMMAND)
2192 write_stderr(_("%s: no database directory specified and environment variable PGDATA unset\n"),
2200 switch (ctl_command)
2202 case RESTART_COMMAND:
2214 if (ctl_command == RELOAD_COMMAND)
2222 snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
2223 snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
2224 snprintf(backup_file, MAXPGPATH, "%s/backup_label", pg_data);
2225 snprintf(recovery_file, MAXPGPATH, "%s/recovery.conf", pg_data);
2226 snprintf(promote_file, MAXPGPATH, "%s/promote", pg_data);
2229 switch (ctl_command)
2234 case STATUS_COMMAND:
2243 case RESTART_COMMAND:
2246 case RELOAD_COMMAND:
2249 case PROMOTE_COMMAND:
2255 #if defined(WIN32) || defined(__CYGWIN__)
2256 case REGISTER_COMMAND:
2257 pgwin32_doRegister();
2259 case UNREGISTER_COMMAND:
2260 pgwin32_doUnregister();
2262 case RUN_AS_SERVICE_COMMAND:
2263 pgwin32_doRunAsService();