PostgreSQL Source Code  git master
pg_ctl.c File Reference
#include "postgres_fe.h"
#include <fcntl.h>
#include <signal.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include "catalog/pg_control.h"
#include "common/controldata_utils.h"
#include "common/file_perm.h"
#include "common/logging.h"
#include "common/string.h"
#include "getopt_long.h"
#include "utils/pidfile.h"
Include dependency graph for pg_ctl.c:

Go to the source code of this file.

Macros

#define DEFAULT_WAIT   60
 
#define USEC_PER_SEC   1000000
 
#define WAITS_PER_SEC   10 /* should divide USEC_PER_SEC evenly */
 

Typedefs

typedef long pgpid_t
 

Enumerations

enum  ShutdownMode { SMART_MODE, FAST_MODE, IMMEDIATE_MODE }
 
enum  WaitPMResult { POSTMASTER_READY, POSTMASTER_STILL_STARTING, POSTMASTER_FAILED }
 
enum  CtlCommand {
  NO_COMMAND = 0, INIT_COMMAND, START_COMMAND, STOP_COMMAND,
  RESTART_COMMAND, RELOAD_COMMAND, STATUS_COMMAND, PROMOTE_COMMAND,
  LOGROTATE_COMMAND, KILL_COMMAND, REGISTER_COMMAND, UNREGISTER_COMMAND,
  RUN_AS_SERVICE_COMMAND
}
 

Functions

static void write_stderr (const char *fmt,...) pg_attribute_printf(1
 
static void static void do_advice (void)
 
static void do_help (void)
 
static void set_mode (char *modeopt)
 
static void set_sig (char *signame)
 
static void do_init (void)
 
static void do_start (void)
 
static void do_stop (void)
 
static void do_restart (void)
 
static void do_reload (void)
 
static void do_status (void)
 
static void do_promote (void)
 
static void do_logrotate (void)
 
static void do_kill (pgpid_t pid)
 
static void print_msg (const char *msg)
 
static void adjust_data_dir (void)
 
static pgpid_t get_pgpid (bool is_status_request)
 
static char ** readfile (const char *path, int *numlines)
 
static void free_readfile (char **optlines)
 
static pgpid_t start_postmaster (void)
 
static void read_post_opts (void)
 
static WaitPMResult wait_for_postmaster (pgpid_t pm_pid, bool do_checkpoint)
 
static bool postmaster_is_alive (pid_t pid)
 
static DBState get_control_dbstate (void)
 
static void trap_sigint_during_startup (int sig)
 
static char * find_other_exec_or_die (const char *argv0, const char *target, const char *versionstr)
 
int main (int argc, char **argv)
 

Variables

static bool do_wait = true
 
static int wait_seconds = DEFAULT_WAIT
 
static bool wait_seconds_arg = false
 
static bool silent_mode = false
 
static ShutdownMode shutdown_mode = FAST_MODE
 
static int sig = SIGINT
 
static CtlCommand ctl_command = NO_COMMAND
 
static char * pg_data = NULL
 
static char * pg_config = NULL
 
static char * pgdata_opt = NULL
 
static char * post_opts = NULL
 
static const char * progname
 
static char * log_file = NULL
 
static char * exec_path = NULL
 
static char * event_source = NULL
 
static char * register_servicename = "PostgreSQL"
 
static char * register_username = NULL
 
static char * register_password = NULL
 
static char * argv0 = NULL
 
static bool allow_core_files = false
 
static time_t start_time
 
static char postopts_file [MAXPGPATH]
 
static char version_file [MAXPGPATH]
 
static char pid_file [MAXPGPATH]
 
static char backup_file [MAXPGPATH]
 
static char promote_file [MAXPGPATH]
 
static char logrotate_file [MAXPGPATH]
 
static volatile pgpid_t postmasterPID = -1
 

Macro Definition Documentation

◆ DEFAULT_WAIT

#define DEFAULT_WAIT   60

Definition at line 73 of file pg_ctl.c.

Referenced by do_kill().

◆ USEC_PER_SEC

#define USEC_PER_SEC   1000000

Definition at line 75 of file pg_ctl.c.

Referenced by do_promote(), do_restart(), do_stop(), and wait_for_postmaster().

◆ WAITS_PER_SEC

#define WAITS_PER_SEC   10 /* should divide USEC_PER_SEC evenly */

Definition at line 77 of file pg_ctl.c.

Referenced by do_promote(), do_restart(), do_stop(), and wait_for_postmaster().

Typedef Documentation

◆ pgpid_t

typedef long pgpid_t

Definition at line 39 of file pg_ctl.c.

Enumeration Type Documentation

◆ CtlCommand

enum CtlCommand
Enumerator
NO_COMMAND 
INIT_COMMAND 
START_COMMAND 
STOP_COMMAND 
RESTART_COMMAND 
RELOAD_COMMAND 
STATUS_COMMAND 
PROMOTE_COMMAND 
LOGROTATE_COMMAND 
KILL_COMMAND 
REGISTER_COMMAND 
UNREGISTER_COMMAND 
RUN_AS_SERVICE_COMMAND 

Definition at line 56 of file pg_ctl.c.

◆ ShutdownMode

Enumerator
SMART_MODE 
FAST_MODE 
IMMEDIATE_MODE 

Definition at line 42 of file pg_ctl.c.

43 {
44  SMART_MODE,
45  FAST_MODE,
47 } ShutdownMode;
ShutdownMode
Definition: pg_ctl.c:42

◆ WaitPMResult

Enumerator
POSTMASTER_READY 
POSTMASTER_STILL_STARTING 
POSTMASTER_FAILED 

Definition at line 49 of file pg_ctl.c.

Function Documentation

◆ adjust_data_dir()

static void adjust_data_dir ( void  )
static

Definition at line 2183 of file pg_ctl.c.

References _, argv0, canonicalize_path(), exec_path, fd(), filename, find_other_exec_or_die(), free, MAXPGPATH, my_exec_path, PG_BACKEND_VERSIONSTR, pg_config, pg_data, pg_strdup(), pg_strip_crlf(), pgdata_opt, post_opts, progname, snprintf, and write_stderr().

Referenced by main().

2184 {
2185  char cmd[MAXPGPATH],
2187  *my_exec_path;
2188  FILE *fd;
2189 
2190  /* do nothing if we're working without knowledge of data dir */
2191  if (pg_config == NULL)
2192  return;
2193 
2194  /* If there is no postgresql.conf, it can't be a config-only dir */
2195  snprintf(filename, sizeof(filename), "%s/postgresql.conf", pg_config);
2196  if ((fd = fopen(filename, "r")) == NULL)
2197  return;
2198  fclose(fd);
2199 
2200  /* If PG_VERSION exists, it can't be a config-only dir */
2201  snprintf(filename, sizeof(filename), "%s/PG_VERSION", pg_config);
2202  if ((fd = fopen(filename, "r")) != NULL)
2203  {
2204  fclose(fd);
2205  return;
2206  }
2207 
2208  /* Must be a configuration directory, so find the data directory */
2209 
2210  /* we use a private my_exec_path to avoid interfering with later uses */
2211  if (exec_path == NULL)
2212  my_exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
2213  else
2214  my_exec_path = pg_strdup(exec_path);
2215 
2216  /* it's important for -C to be the first option, see main.c */
2217  snprintf(cmd, MAXPGPATH, "\"%s\" -C data_directory %s%s",
2218  my_exec_path,
2219  pgdata_opt ? pgdata_opt : "",
2220  post_opts ? post_opts : "");
2221 
2222  fd = popen(cmd, "r");
2223  if (fd == NULL || fgets(filename, sizeof(filename), fd) == NULL)
2224  {
2225  write_stderr(_("%s: could not determine the data directory using command \"%s\"\n"), progname, cmd);
2226  exit(1);
2227  }
2228  pclose(fd);
2229  free(my_exec_path);
2230 
2231  /* strip trailing newline and carriage return */
2232  (void) pg_strip_crlf(filename);
2233 
2234  free(pg_data);
2235  pg_data = pg_strdup(filename);
2237 }
static char * argv0
Definition: pg_ctl.c:97
int pg_strip_crlf(char *str)
Definition: string.c:105
static char * post_opts
Definition: pg_ctl.c:89
void canonicalize_path(char *path)
Definition: path.c:254
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static char * pg_data
Definition: pg_ctl.c:86
#define MAXPGPATH
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
char my_exec_path[MAXPGPATH]
Definition: globals.c:72
static char * pgdata_opt
Definition: pg_ctl.c:88
#define PG_BACKEND_VERSIONSTR
Definition: port.h:112
#define free(a)
Definition: header.h:65
static char * exec_path
Definition: pg_ctl.c:92
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
static char * filename
Definition: pg_dumpall.c:90
#define snprintf
Definition: port.h:193
#define _(x)
Definition: elog.c:88
static char * find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
Definition: pg_ctl.c:798
static char * pg_config
Definition: pg_ctl.c:87

◆ do_advice()

static void do_advice ( void  )
static

Definition at line 2023 of file pg_ctl.c.

References _, progname, and write_stderr().

Referenced by main(), set_mode(), and set_sig().

2024 {
2025  write_stderr(_("Try \"%s --help\" for more information.\n"), progname);
2026 }
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
#define _(x)
Definition: elog.c:88

◆ do_help()

static void do_help ( void  )
static

Definition at line 2031 of file pg_ctl.c.

References _, printf, and progname.

Referenced by main().

2032 {
2033  printf(_("%s is a utility to initialize, start, stop, or control a PostgreSQL server.\n\n"), progname);
2034  printf(_("Usage:\n"));
2035  printf(_(" %s init[db] [-D DATADIR] [-s] [-o OPTIONS]\n"), progname);
2036  printf(_(" %s start [-D DATADIR] [-l FILENAME] [-W] [-t SECS] [-s]\n"
2037  " [-o OPTIONS] [-p PATH] [-c]\n"), progname);
2038  printf(_(" %s stop [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s]\n"), progname);
2039  printf(_(" %s restart [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s]\n"
2040  " [-o OPTIONS] [-c]\n"), progname);
2041  printf(_(" %s reload [-D DATADIR] [-s]\n"), progname);
2042  printf(_(" %s status [-D DATADIR]\n"), progname);
2043  printf(_(" %s promote [-D DATADIR] [-W] [-t SECS] [-s]\n"), progname);
2044  printf(_(" %s logrotate [-D DATADIR] [-s]\n"), progname);
2045  printf(_(" %s kill SIGNALNAME PID\n"), progname);
2046 #ifdef WIN32
2047  printf(_(" %s register [-D DATADIR] [-N SERVICENAME] [-U USERNAME] [-P PASSWORD]\n"
2048  " [-S START-TYPE] [-e SOURCE] [-W] [-t SECS] [-s] [-o OPTIONS]\n"), progname);
2049  printf(_(" %s unregister [-N SERVICENAME]\n"), progname);
2050 #endif
2051 
2052  printf(_("\nCommon options:\n"));
2053  printf(_(" -D, --pgdata=DATADIR location of the database storage area\n"));
2054 #ifdef WIN32
2055  printf(_(" -e SOURCE event source for logging when running as a service\n"));
2056 #endif
2057  printf(_(" -s, --silent only print errors, no informational messages\n"));
2058  printf(_(" -t, --timeout=SECS seconds to wait when using -w option\n"));
2059  printf(_(" -V, --version output version information, then exit\n"));
2060  printf(_(" -w, --wait wait until operation completes (default)\n"));
2061  printf(_(" -W, --no-wait do not wait until operation completes\n"));
2062  printf(_(" -?, --help show this help, then exit\n"));
2063  printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
2064 
2065  printf(_("\nOptions for start or restart:\n"));
2066 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
2067  printf(_(" -c, --core-files allow postgres to produce core files\n"));
2068 #else
2069  printf(_(" -c, --core-files not applicable on this platform\n"));
2070 #endif
2071  printf(_(" -l, --log=FILENAME write (or append) server log to FILENAME\n"));
2072  printf(_(" -o, --options=OPTIONS command line options to pass to postgres\n"
2073  " (PostgreSQL server executable) or initdb\n"));
2074  printf(_(" -p PATH-TO-POSTGRES normally not necessary\n"));
2075  printf(_("\nOptions for stop or restart:\n"));
2076  printf(_(" -m, --mode=MODE MODE can be \"smart\", \"fast\", or \"immediate\"\n"));
2077 
2078  printf(_("\nShutdown modes are:\n"));
2079  printf(_(" smart quit after all clients have disconnected\n"));
2080  printf(_(" fast quit directly, with proper shutdown (default)\n"));
2081  printf(_(" immediate quit without complete shutdown; will lead to recovery on restart\n"));
2082 
2083  printf(_("\nAllowed signal names for kill:\n"));
2084  printf(" ABRT HUP INT KILL QUIT TERM USR1 USR2\n");
2085 
2086 #ifdef WIN32
2087  printf(_("\nOptions for register and unregister:\n"));
2088  printf(_(" -N SERVICENAME service name with which to register PostgreSQL server\n"));
2089  printf(_(" -P PASSWORD password of account to register PostgreSQL server\n"));
2090  printf(_(" -U USERNAME user name of account to register PostgreSQL server\n"));
2091  printf(_(" -S START-TYPE service start type to register PostgreSQL server\n"));
2092 
2093  printf(_("\nStart types are:\n"));
2094  printf(_(" auto start service automatically during system startup (default)\n"));
2095  printf(_(" demand start service on demand\n"));
2096 #endif
2097 
2098  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
2099  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
2100 }
#define printf(...)
Definition: port.h:199
static const char * progname
Definition: pg_ctl.c:90
#define _(x)
Definition: elog.c:88

◆ do_init()

static void do_init ( void  )
static

Definition at line 830 of file pg_ctl.c.

References _, argv0, DEVNULL, exec_path, find_other_exec_or_die(), MAXPGPATH, pgdata_opt, post_opts, progname, silent_mode, snprintf, and write_stderr().

Referenced by main().

831 {
832  char cmd[MAXPGPATH];
833 
834  if (exec_path == NULL)
835  exec_path = find_other_exec_or_die(argv0, "initdb", "initdb (PostgreSQL) " PG_VERSION "\n");
836 
837  if (pgdata_opt == NULL)
838  pgdata_opt = "";
839 
840  if (post_opts == NULL)
841  post_opts = "";
842 
843  if (!silent_mode)
844  snprintf(cmd, MAXPGPATH, "\"%s\" %s%s",
846  else
847  snprintf(cmd, MAXPGPATH, "\"%s\" %s%s > \"%s\"",
849 
850  if (system(cmd) != 0)
851  {
852  write_stderr(_("%s: database system initialization failed\n"), progname);
853  exit(1);
854  }
855 }
static char * argv0
Definition: pg_ctl.c:97
static char * post_opts
Definition: pg_ctl.c:89
#define MAXPGPATH
#define DEVNULL
Definition: port.h:124
static char * pgdata_opt
Definition: pg_ctl.c:88
static char * exec_path
Definition: pg_ctl.c:92
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
#define snprintf
Definition: port.h:193
#define _(x)
Definition: elog.c:88
static char * find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
Definition: pg_ctl.c:798
static bool silent_mode
Definition: pg_ctl.c:82

◆ do_kill()

static void do_kill ( pgpid_t  pid)
static

Definition at line 1406 of file pg_ctl.c.

References _, AddUserToTokenDacl(), appendPQExpBuffer(), appendPQExpBufferStr(), argv0, createPQExpBuffer(), PQExpBufferData::data, DEFAULT_WAIT, do_wait, event_source, find_my_exec(), find_other_exec(), free, i, kill, make_absolute_path(), make_native_path(), MAXPGPATH, MCXT_ALLOC_NO_OOM, PG_BACKEND_VERSIONSTR, pg_config, pg_malloc_extended(), pg_strcasecmp(), post_opts, POSTMASTER_READY, postmasterPID, progname, read_post_opts(), register_password, register_servicename, register_username, sig, SIGHUP, silent_mode, snprintf, sprintf, status(), strerror, wait_for_postmaster(), wait_seconds, wait_seconds_arg, and write_stderr().

Referenced by main().

1407 {
1408  if (kill((pid_t) pid, sig) != 0)
1409  {
1410  write_stderr(_("%s: could not send signal %d (PID: %ld): %s\n"),
1411  progname, sig, pid, strerror(errno));
1412  exit(1);
1413  }
1414 }
#define kill(pid, sig)
Definition: win32_port.h:426
static int sig
Definition: pg_ctl.c:84
#define strerror
Definition: port.h:206
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
#define _(x)
Definition: elog.c:88

◆ do_logrotate()

static void do_logrotate ( void  )
static

Definition at line 1268 of file pg_ctl.c.

References _, get_pgpid(), kill, logrotate_file, MAXPGPATH, pg_data, pid_file, print_msg(), progname, sig, SIGUSR1, snprintf, strerror, and write_stderr().

Referenced by main().

1269 {
1270  FILE *logrotatefile;
1271  pgpid_t pid;
1272 
1273  pid = get_pgpid(false);
1274 
1275  if (pid == 0) /* no pid file */
1276  {
1277  write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1278  write_stderr(_("Is server running?\n"));
1279  exit(1);
1280  }
1281  else if (pid < 0) /* standalone backend, not postmaster */
1282  {
1283  pid = -pid;
1284  write_stderr(_("%s: cannot rotate log file; "
1285  "single-user server is running (PID: %ld)\n"),
1286  progname, pid);
1287  exit(1);
1288  }
1289 
1290  snprintf(logrotate_file, MAXPGPATH, "%s/logrotate", pg_data);
1291 
1292  if ((logrotatefile = fopen(logrotate_file, "w")) == NULL)
1293  {
1294  write_stderr(_("%s: could not create log rotation signal file \"%s\": %s\n"),
1295  progname, logrotate_file, strerror(errno));
1296  exit(1);
1297  }
1298  if (fclose(logrotatefile))
1299  {
1300  write_stderr(_("%s: could not write log rotation signal file \"%s\": %s\n"),
1301  progname, logrotate_file, strerror(errno));
1302  exit(1);
1303  }
1304 
1305  sig = SIGUSR1;
1306  if (kill((pid_t) pid, sig) != 0)
1307  {
1308  write_stderr(_("%s: could not send log rotation signal (PID: %ld): %s\n"),
1309  progname, pid, strerror(errno));
1310  if (unlink(logrotate_file) != 0)
1311  write_stderr(_("%s: could not remove log rotation signal file \"%s\": %s\n"),
1312  progname, logrotate_file, strerror(errno));
1313  exit(1);
1314  }
1315 
1316  print_msg(_("server signaled to rotate log file\n"));
1317 }
static char logrotate_file[MAXPGPATH]
Definition: pg_ctl.c:106
#define SIGUSR1
Definition: win32_port.h:165
#define kill(pid, sig)
Definition: win32_port.h:426
static char * pg_data
Definition: pg_ctl.c:86
static char pid_file[MAXPGPATH]
Definition: pg_ctl.c:103
long pgpid_t
Definition: pg_ctl.c:39
#define MAXPGPATH
static pgpid_t get_pgpid(bool is_status_request)
Definition: pg_ctl.c:249
static int sig
Definition: pg_ctl.c:84
#define strerror
Definition: port.h:206
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
#define snprintf
Definition: port.h:193
static void print_msg(const char *msg)
Definition: pg_ctl.c:239
#define _(x)
Definition: elog.c:88

◆ do_promote()

static void do_promote ( void  )
static

Definition at line 1169 of file pg_ctl.c.

References _, DB_IN_ARCHIVE_RECOVERY, DB_IN_PRODUCTION, DB_STARTUP, do_wait, get_control_dbstate(), get_pgpid(), kill, MAXPGPATH, pg_data, pg_usleep(), pid_file, print_msg(), progname, promote_file, sig, SIGUSR1, snprintf, strerror, USEC_PER_SEC, wait_seconds, WAITS_PER_SEC, and write_stderr().

Referenced by main().

1170 {
1171  FILE *prmfile;
1172  pgpid_t pid;
1173 
1174  pid = get_pgpid(false);
1175 
1176  if (pid == 0) /* no pid file */
1177  {
1178  write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1179  write_stderr(_("Is server running?\n"));
1180  exit(1);
1181  }
1182  else if (pid < 0) /* standalone backend, not postmaster */
1183  {
1184  pid = -pid;
1185  write_stderr(_("%s: cannot promote server; "
1186  "single-user server is running (PID: %ld)\n"),
1187  progname, pid);
1188  exit(1);
1189  }
1190 
1192  {
1193  write_stderr(_("%s: cannot promote server; "
1194  "server is not in standby mode\n"),
1195  progname);
1196  exit(1);
1197  }
1198 
1199  /*
1200  * For 9.3 onwards, "fast" promotion is performed. Promotion with a full
1201  * checkpoint is still possible by writing a file called
1202  * "fallback_promote" instead of "promote"
1203  */
1204  snprintf(promote_file, MAXPGPATH, "%s/promote", pg_data);
1205 
1206  if ((prmfile = fopen(promote_file, "w")) == NULL)
1207  {
1208  write_stderr(_("%s: could not create promote signal file \"%s\": %s\n"),
1209  progname, promote_file, strerror(errno));
1210  exit(1);
1211  }
1212  if (fclose(prmfile))
1213  {
1214  write_stderr(_("%s: could not write promote signal file \"%s\": %s\n"),
1215  progname, promote_file, strerror(errno));
1216  exit(1);
1217  }
1218 
1219  sig = SIGUSR1;
1220  if (kill((pid_t) pid, sig) != 0)
1221  {
1222  write_stderr(_("%s: could not send promote signal (PID: %ld): %s\n"),
1223  progname, pid, strerror(errno));
1224  if (unlink(promote_file) != 0)
1225  write_stderr(_("%s: could not remove promote signal file \"%s\": %s\n"),
1226  progname, promote_file, strerror(errno));
1227  exit(1);
1228  }
1229 
1230  if (do_wait)
1231  {
1233  int cnt;
1234 
1235  print_msg(_("waiting for server to promote..."));
1236  for (cnt = 0; cnt < wait_seconds * WAITS_PER_SEC; cnt++)
1237  {
1238  state = get_control_dbstate();
1239  if (state == DB_IN_PRODUCTION)
1240  break;
1241 
1242  if (cnt % WAITS_PER_SEC == 0)
1243  print_msg(".");
1244  pg_usleep(USEC_PER_SEC / WAITS_PER_SEC);
1245  }
1246  if (state == DB_IN_PRODUCTION)
1247  {
1248  print_msg(_(" done\n"));
1249  print_msg(_("server promoted\n"));
1250  }
1251  else
1252  {
1253  print_msg(_(" stopped waiting\n"));
1254  write_stderr(_("%s: server did not promote in time\n"),
1255  progname);
1256  exit(1);
1257  }
1258  }
1259  else
1260  print_msg(_("server promoting\n"));
1261 }
static int wait_seconds
Definition: pg_ctl.c:80
#define SIGUSR1
Definition: win32_port.h:165
#define kill(pid, sig)
Definition: win32_port.h:426
static char * pg_data
Definition: pg_ctl.c:86
void pg_usleep(long microsec)
Definition: signal.c:53
static char pid_file[MAXPGPATH]
Definition: pg_ctl.c:103
long pgpid_t
Definition: pg_ctl.c:39
#define MAXPGPATH
#define USEC_PER_SEC
Definition: pg_ctl.c:75
DBState
Definition: pg_control.h:85
static pgpid_t get_pgpid(bool is_status_request)
Definition: pg_ctl.c:249
static int sig
Definition: pg_ctl.c:84
Definition: regguts.h:298
#define strerror
Definition: port.h:206
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
static char promote_file[MAXPGPATH]
Definition: pg_ctl.c:105
static bool do_wait
Definition: pg_ctl.c:79
static DBState get_control_dbstate(void)
Definition: pg_ctl.c:2241
#define snprintf
Definition: port.h:193
static void print_msg(const char *msg)
Definition: pg_ctl.c:239
#define _(x)
Definition: elog.c:88
#define WAITS_PER_SEC
Definition: pg_ctl.c:77

◆ do_reload()

static void do_reload ( void  )
static

Definition at line 1132 of file pg_ctl.c.

References _, get_pgpid(), kill, pid_file, print_msg(), progname, sig, strerror, and write_stderr().

Referenced by main().

1133 {
1134  pgpid_t pid;
1135 
1136  pid = get_pgpid(false);
1137  if (pid == 0) /* no pid file */
1138  {
1139  write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1140  write_stderr(_("Is server running?\n"));
1141  exit(1);
1142  }
1143  else if (pid < 0) /* standalone backend, not postmaster */
1144  {
1145  pid = -pid;
1146  write_stderr(_("%s: cannot reload server; "
1147  "single-user server is running (PID: %ld)\n"),
1148  progname, pid);
1149  write_stderr(_("Please terminate the single-user server and try again.\n"));
1150  exit(1);
1151  }
1152 
1153  if (kill((pid_t) pid, sig) != 0)
1154  {
1155  write_stderr(_("%s: could not send reload signal (PID: %ld): %s\n"),
1156  progname, pid, strerror(errno));
1157  exit(1);
1158  }
1159 
1160  print_msg(_("server signaled\n"));
1161 }
#define kill(pid, sig)
Definition: win32_port.h:426
static char pid_file[MAXPGPATH]
Definition: pg_ctl.c:103
long pgpid_t
Definition: pg_ctl.c:39
static pgpid_t get_pgpid(bool is_status_request)
Definition: pg_ctl.c:249
static int sig
Definition: pg_ctl.c:84
#define strerror
Definition: port.h:206
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
static void print_msg(const char *msg)
Definition: pg_ctl.c:239
#define _(x)
Definition: elog.c:88

◆ do_restart()

static void do_restart ( void  )
static

Definition at line 1038 of file pg_ctl.c.

References _, backup_file, DB_IN_ARCHIVE_RECOVERY, do_start(), get_control_dbstate(), get_pgpid(), kill, pg_usleep(), pid_file, postmaster_is_alive(), print_msg(), progname, shutdown_mode, sig, SMART_MODE, stat, strerror, USEC_PER_SEC, wait_seconds, WAITS_PER_SEC, and write_stderr().

Referenced by main().

1039 {
1040  int cnt;
1041  pgpid_t pid;
1042  struct stat statbuf;
1043 
1044  pid = get_pgpid(false);
1045 
1046  if (pid == 0) /* no pid file */
1047  {
1048  write_stderr(_("%s: PID file \"%s\" does not exist\n"),
1049  progname, pid_file);
1050  write_stderr(_("Is server running?\n"));
1051  write_stderr(_("trying to start server anyway\n"));
1052  do_start();
1053  return;
1054  }
1055  else if (pid < 0) /* standalone backend, not postmaster */
1056  {
1057  pid = -pid;
1058  if (postmaster_is_alive((pid_t) pid))
1059  {
1060  write_stderr(_("%s: cannot restart server; "
1061  "single-user server is running (PID: %ld)\n"),
1062  progname, pid);
1063  write_stderr(_("Please terminate the single-user server and try again.\n"));
1064  exit(1);
1065  }
1066  }
1067 
1068  if (postmaster_is_alive((pid_t) pid))
1069  {
1070  if (kill((pid_t) pid, sig) != 0)
1071  {
1072  write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
1073  strerror(errno));
1074  exit(1);
1075  }
1076 
1077  /*
1078  * If backup_label exists, an online backup is running. Warn the user
1079  * that smart shutdown will wait for it to finish. However, if the
1080  * server is in archive recovery, we're recovering from an online
1081  * backup instead of performing one.
1082  */
1083  if (shutdown_mode == SMART_MODE &&
1084  stat(backup_file, &statbuf) == 0 &&
1086  {
1087  print_msg(_("WARNING: online backup mode is active\n"
1088  "Shutdown will not complete until pg_stop_backup() is called.\n\n"));
1089  }
1090 
1091  print_msg(_("waiting for server to shut down..."));
1092 
1093  /* always wait for restart */
1094 
1095  for (cnt = 0; cnt < wait_seconds * WAITS_PER_SEC; cnt++)
1096  {
1097  if ((pid = get_pgpid(false)) != 0)
1098  {
1099  if (cnt % WAITS_PER_SEC == 0)
1100  print_msg(".");
1101  pg_usleep(USEC_PER_SEC / WAITS_PER_SEC);
1102  }
1103  else
1104  break;
1105  }
1106 
1107  if (pid != 0) /* pid file still exists */
1108  {
1109  print_msg(_(" failed\n"));
1110 
1111  write_stderr(_("%s: server does not shut down\n"), progname);
1112  if (shutdown_mode == SMART_MODE)
1113  write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1114  "waiting for session-initiated disconnection.\n"));
1115  exit(1);
1116  }
1117 
1118  print_msg(_(" done\n"));
1119  print_msg(_("server stopped\n"));
1120  }
1121  else
1122  {
1123  write_stderr(_("%s: old server process (PID: %ld) seems to be gone\n"),
1124  progname, pid);
1125  write_stderr(_("starting server anyway\n"));
1126  }
1127 
1128  do_start();
1129 }
static int wait_seconds
Definition: pg_ctl.c:80
#define kill(pid, sig)
Definition: win32_port.h:426
static ShutdownMode shutdown_mode
Definition: pg_ctl.c:83
void pg_usleep(long microsec)
Definition: signal.c:53
static char pid_file[MAXPGPATH]
Definition: pg_ctl.c:103
long pgpid_t
Definition: pg_ctl.c:39
static char backup_file[MAXPGPATH]
Definition: pg_ctl.c:104
static void do_start(void)
Definition: pg_ctl.c:858
#define USEC_PER_SEC
Definition: pg_ctl.c:75
#define stat(a, b)
Definition: win32_port.h:255
static pgpid_t get_pgpid(bool is_status_request)
Definition: pg_ctl.c:249
static int sig
Definition: pg_ctl.c:84
#define strerror
Definition: port.h:206
static bool postmaster_is_alive(pid_t pid)
Definition: pg_ctl.c:1325
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
static DBState get_control_dbstate(void)
Definition: pg_ctl.c:2241
static void print_msg(const char *msg)
Definition: pg_ctl.c:239
#define _(x)
Definition: elog.c:88
#define WAITS_PER_SEC
Definition: pg_ctl.c:77

◆ do_start()

static void do_start ( void  )
static

Definition at line 858 of file pg_ctl.c.

References _, allow_core_files, argv0, ctl_command, do_wait, exec_path, find_other_exec_or_die(), get_pgpid(), PG_BACKEND_VERSIONSTR, pgdata_opt, POSTMASTER_FAILED, POSTMASTER_READY, POSTMASTER_STILL_STARTING, postmasterPID, pqsignal(), print_msg(), progname, putenv, read_post_opts(), RESTART_COMMAND, snprintf, start_postmaster(), trap_sigint_during_startup(), wait_for_postmaster(), and write_stderr().

Referenced by do_restart(), and main().

859 {
860  pgpid_t old_pid = 0;
861  pgpid_t pm_pid;
862 
864  {
865  old_pid = get_pgpid(false);
866  if (old_pid != 0)
867  write_stderr(_("%s: another server might be running; "
868  "trying to start server anyway\n"),
869  progname);
870  }
871 
872  read_post_opts();
873 
874  /* No -D or -D already added during server start */
875  if (ctl_command == RESTART_COMMAND || pgdata_opt == NULL)
876  pgdata_opt = "";
877 
878  if (exec_path == NULL)
880 
881 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
882  if (allow_core_files)
883  unlimit_core_size();
884 #endif
885 
886  /*
887  * If possible, tell the postmaster our parent shell's PID (see the
888  * comments in CreateLockFile() for motivation). Windows hasn't got
889  * getppid() unfortunately.
890  */
891 #ifndef WIN32
892  {
893  static char env_var[32];
894 
895  snprintf(env_var, sizeof(env_var), "PG_GRANDPARENT_PID=%d",
896  (int) getppid());
897  putenv(env_var);
898  }
899 #endif
900 
901  pm_pid = start_postmaster();
902 
903  if (do_wait)
904  {
905  /*
906  * If the user interrupts the startup (e.g. with CTRL-C), we'd like to
907  * abort the server launch. Install a signal handler that will
908  * forward SIGINT to the postmaster process, while we wait.
909  *
910  * (We don't bother to reset the signal handler after the launch, as
911  * we're about to exit, anyway.)
912  */
913  postmasterPID = pm_pid;
915 
916  print_msg(_("waiting for server to start..."));
917 
918  switch (wait_for_postmaster(pm_pid, false))
919  {
920  case POSTMASTER_READY:
921  print_msg(_(" done\n"));
922  print_msg(_("server started\n"));
923  break;
925  print_msg(_(" stopped waiting\n"));
926  write_stderr(_("%s: server did not start in time\n"),
927  progname);
928  exit(1);
929  break;
930  case POSTMASTER_FAILED:
931  print_msg(_(" stopped waiting\n"));
932  write_stderr(_("%s: could not start server\n"
933  "Examine the log output.\n"),
934  progname);
935  exit(1);
936  break;
937  }
938  }
939  else
940  print_msg(_("server starting\n"));
941 
942 #ifdef WIN32
943  /* Now we don't need the handle to the shell process anymore */
944  CloseHandle(postmasterProcess);
945  postmasterProcess = INVALID_HANDLE_VALUE;
946 #endif
947 }
static char * argv0
Definition: pg_ctl.c:97
static void read_post_opts(void)
Definition: pg_ctl.c:725
long pgpid_t
Definition: pg_ctl.c:39
static void trap_sigint_during_startup(int sig)
Definition: pg_ctl.c:780
static pgpid_t get_pgpid(bool is_status_request)
Definition: pg_ctl.c:249
static volatile pgpid_t postmasterPID
Definition: pg_ctl.c:108
static char * pgdata_opt
Definition: pg_ctl.c:88
#define PG_BACKEND_VERSIONSTR
Definition: port.h:112
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static WaitPMResult wait_for_postmaster(pgpid_t pm_pid, bool do_checkpoint)
Definition: pg_ctl.c:593
static bool allow_core_files
Definition: pg_ctl.c:98
static char * exec_path
Definition: pg_ctl.c:92
#define putenv(x)
Definition: win32_port.h:474
static const char * progname
Definition: pg_ctl.c:90
static pgpid_t start_postmaster(void)
Definition: pg_ctl.c:443
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
static bool do_wait
Definition: pg_ctl.c:79
#define snprintf
Definition: port.h:193
static CtlCommand ctl_command
Definition: pg_ctl.c:85
static void print_msg(const char *msg)
Definition: pg_ctl.c:239
#define _(x)
Definition: elog.c:88
static char * find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
Definition: pg_ctl.c:798

◆ do_status()

static void do_status ( void  )
static

Definition at line 1349 of file pg_ctl.c.

References _, free_readfile(), get_pgpid(), postmaster_is_alive(), postopts_file, printf, progname, and readfile().

Referenced by main().

1350 {
1351  pgpid_t pid;
1352 
1353  pid = get_pgpid(true);
1354  /* Is there a pid file? */
1355  if (pid != 0)
1356  {
1357  /* standalone backend? */
1358  if (pid < 0)
1359  {
1360  pid = -pid;
1361  if (postmaster_is_alive((pid_t) pid))
1362  {
1363  printf(_("%s: single-user server is running (PID: %ld)\n"),
1364  progname, pid);
1365  return;
1366  }
1367  }
1368  else
1369  /* must be a postmaster */
1370  {
1371  if (postmaster_is_alive((pid_t) pid))
1372  {
1373  char **optlines;
1374  char **curr_line;
1375  int numlines;
1376 
1377  printf(_("%s: server is running (PID: %ld)\n"),
1378  progname, pid);
1379 
1380  optlines = readfile(postopts_file, &numlines);
1381  if (optlines != NULL)
1382  {
1383  for (curr_line = optlines; *curr_line != NULL; curr_line++)
1384  puts(*curr_line);
1385 
1386  /* Free the results of readfile */
1387  free_readfile(optlines);
1388  }
1389  return;
1390  }
1391  }
1392  }
1393  printf(_("%s: no server running\n"), progname);
1394 
1395  /*
1396  * The Linux Standard Base Core Specification 3.1 says this should return
1397  * '3, program is not running'
1398  * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
1399  */
1400  exit(3);
1401 }
#define printf(...)
Definition: port.h:199
static char ** readfile(const char *path, int *numlines)
Definition: pg_ctl.c:317
long pgpid_t
Definition: pg_ctl.c:39
static pgpid_t get_pgpid(bool is_status_request)
Definition: pg_ctl.c:249
static char postopts_file[MAXPGPATH]
Definition: pg_ctl.c:101
static void free_readfile(char **optlines)
Definition: pg_ctl.c:413
static bool postmaster_is_alive(pid_t pid)
Definition: pg_ctl.c:1325
static const char * progname
Definition: pg_ctl.c:90
#define _(x)
Definition: elog.c:88

◆ do_stop()

static void do_stop ( void  )
static

Definition at line 951 of file pg_ctl.c.

References _, backup_file, DB_IN_ARCHIVE_RECOVERY, do_wait, get_control_dbstate(), get_pgpid(), kill, pg_usleep(), pid_file, print_msg(), progname, shutdown_mode, sig, SMART_MODE, stat, strerror, USEC_PER_SEC, wait_seconds, WAITS_PER_SEC, and write_stderr().

Referenced by main().

952 {
953  int cnt;
954  pgpid_t pid;
955  struct stat statbuf;
956 
957  pid = get_pgpid(false);
958 
959  if (pid == 0) /* no pid file */
960  {
961  write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
962  write_stderr(_("Is server running?\n"));
963  exit(1);
964  }
965  else if (pid < 0) /* standalone backend, not postmaster */
966  {
967  pid = -pid;
968  write_stderr(_("%s: cannot stop server; "
969  "single-user server is running (PID: %ld)\n"),
970  progname, pid);
971  exit(1);
972  }
973 
974  if (kill((pid_t) pid, sig) != 0)
975  {
976  write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
977  strerror(errno));
978  exit(1);
979  }
980 
981  if (!do_wait)
982  {
983  print_msg(_("server shutting down\n"));
984  return;
985  }
986  else
987  {
988  /*
989  * If backup_label exists, an online backup is running. Warn the user
990  * that smart shutdown will wait for it to finish. However, if the
991  * server is in archive recovery, we're recovering from an online
992  * backup instead of performing one.
993  */
994  if (shutdown_mode == SMART_MODE &&
995  stat(backup_file, &statbuf) == 0 &&
997  {
998  print_msg(_("WARNING: online backup mode is active\n"
999  "Shutdown will not complete until pg_stop_backup() is called.\n\n"));
1000  }
1001 
1002  print_msg(_("waiting for server to shut down..."));
1003 
1004  for (cnt = 0; cnt < wait_seconds * WAITS_PER_SEC; cnt++)
1005  {
1006  if ((pid = get_pgpid(false)) != 0)
1007  {
1008  if (cnt % WAITS_PER_SEC == 0)
1009  print_msg(".");
1010  pg_usleep(USEC_PER_SEC / WAITS_PER_SEC);
1011  }
1012  else
1013  break;
1014  }
1015 
1016  if (pid != 0) /* pid file still exists */
1017  {
1018  print_msg(_(" failed\n"));
1019 
1020  write_stderr(_("%s: server does not shut down\n"), progname);
1021  if (shutdown_mode == SMART_MODE)
1022  write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1023  "waiting for session-initiated disconnection.\n"));
1024  exit(1);
1025  }
1026  print_msg(_(" done\n"));
1027 
1028  print_msg(_("server stopped\n"));
1029  }
1030 }
static int wait_seconds
Definition: pg_ctl.c:80
#define kill(pid, sig)
Definition: win32_port.h:426
static ShutdownMode shutdown_mode
Definition: pg_ctl.c:83
void pg_usleep(long microsec)
Definition: signal.c:53
static char pid_file[MAXPGPATH]
Definition: pg_ctl.c:103
long pgpid_t
Definition: pg_ctl.c:39
static char backup_file[MAXPGPATH]
Definition: pg_ctl.c:104
#define USEC_PER_SEC
Definition: pg_ctl.c:75
#define stat(a, b)
Definition: win32_port.h:255
static pgpid_t get_pgpid(bool is_status_request)
Definition: pg_ctl.c:249
static int sig
Definition: pg_ctl.c:84
#define strerror
Definition: port.h:206
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
static bool do_wait
Definition: pg_ctl.c:79
static DBState get_control_dbstate(void)
Definition: pg_ctl.c:2241
static void print_msg(const char *msg)
Definition: pg_ctl.c:239
#define _(x)
Definition: elog.c:88
#define WAITS_PER_SEC
Definition: pg_ctl.c:77

◆ find_other_exec_or_die()

static char* find_other_exec_or_die ( const char *  argv0,
const char *  target,
const char *  versionstr 
)
static

Definition at line 798 of file pg_ctl.c.

References _, find_my_exec(), find_other_exec(), MAXPGPATH, pg_malloc(), progname, strlcpy(), and write_stderr().

Referenced by adjust_data_dir(), do_init(), and do_start().

799 {
800  int ret;
801  char *found_path;
802 
803  found_path = pg_malloc(MAXPGPATH);
804 
805  if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
806  {
807  char full_path[MAXPGPATH];
808 
809  if (find_my_exec(argv0, full_path) < 0)
810  strlcpy(full_path, progname, sizeof(full_path));
811 
812  if (ret == -1)
813  write_stderr(_("The program \"%s\" is needed by %s "
814  "but was not found in the\n"
815  "same directory as \"%s\".\n"
816  "Check your installation.\n"),
817  target, progname, full_path);
818  else
819  write_stderr(_("The program \"%s\" was found by \"%s\"\n"
820  "but was not the same version as %s.\n"
821  "Check your installation.\n"),
822  target, full_path, progname);
823  exit(1);
824  }
825 
826  return found_path;
827 }
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:323
static char * argv0
Definition: pg_ctl.c:97
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
#define MAXPGPATH
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:128
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
#define _(x)
Definition: elog.c:88

◆ free_readfile()

static void free_readfile ( char **  optlines)
static

Definition at line 413 of file pg_ctl.c.

References free, and i.

Referenced by do_status(), read_post_opts(), and wait_for_postmaster().

414 {
415  char *curr_line = NULL;
416  int i = 0;
417 
418  if (!optlines)
419  return;
420 
421  while ((curr_line = optlines[i++]))
422  free(curr_line);
423 
424  free(optlines);
425 }
#define free(a)
Definition: header.h:65
int i

◆ get_control_dbstate()

static DBState get_control_dbstate ( void  )
static

Definition at line 2241 of file pg_ctl.c.

References _, get_controlfile(), pfree(), pg_data, progname, ControlFileData::state, and write_stderr().

Referenced by do_promote(), do_restart(), and do_stop().

2242 {
2243  DBState ret;
2244  bool crc_ok;
2245  ControlFileData *control_file_data = get_controlfile(pg_data, &crc_ok);
2246 
2247  if (!crc_ok)
2248  {
2249  write_stderr(_("%s: control file appears to be corrupt\n"), progname);
2250  exit(1);
2251  }
2252 
2253  ret = control_file_data->state;
2254  pfree(control_file_data);
2255  return ret;
2256 }
static char * pg_data
Definition: pg_ctl.c:86
void pfree(void *pointer)
Definition: mcxt.c:1056
DBState
Definition: pg_control.h:85
ControlFileData * get_controlfile(const char *DataDir, bool *crc_ok_p)
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
#define _(x)
Definition: elog.c:88

◆ get_pgpid()

static pgpid_t get_pgpid ( bool  is_status_request)
static

Definition at line 249 of file pg_ctl.c.

References _, pg_data, pid_file, progname, stat, strerror, version_file, and write_stderr().

Referenced by do_logrotate(), do_promote(), do_reload(), do_restart(), do_start(), do_status(), and do_stop().

250 {
251  FILE *pidf;
252  long pid;
253  struct stat statbuf;
254 
255  if (stat(pg_data, &statbuf) != 0)
256  {
257  if (errno == ENOENT)
258  write_stderr(_("%s: directory \"%s\" does not exist\n"), progname,
259  pg_data);
260  else
261  write_stderr(_("%s: could not access directory \"%s\": %s\n"), progname,
262  pg_data, strerror(errno));
263 
264  /*
265  * The Linux Standard Base Core Specification 3.1 says this should
266  * return '4, program or service status is unknown'
267  * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
268  */
269  exit(is_status_request ? 4 : 1);
270  }
271 
272  if (stat(version_file, &statbuf) != 0 && errno == ENOENT)
273  {
274  write_stderr(_("%s: directory \"%s\" is not a database cluster directory\n"),
275  progname, pg_data);
276  exit(is_status_request ? 4 : 1);
277  }
278 
279  pidf = fopen(pid_file, "r");
280  if (pidf == NULL)
281  {
282  /* No pid file, not an error on startup */
283  if (errno == ENOENT)
284  return 0;
285  else
286  {
287  write_stderr(_("%s: could not open PID file \"%s\": %s\n"),
288  progname, pid_file, strerror(errno));
289  exit(1);
290  }
291  }
292  if (fscanf(pidf, "%ld", &pid) != 1)
293  {
294  /* Is the file empty? */
295  if (ftell(pidf) == 0 && feof(pidf))
296  write_stderr(_("%s: the PID file \"%s\" is empty\n"),
297  progname, pid_file);
298  else
299  write_stderr(_("%s: invalid data in PID file \"%s\"\n"),
300  progname, pid_file);
301  exit(1);
302  }
303  fclose(pidf);
304  return (pgpid_t) pid;
305 }
static char * pg_data
Definition: pg_ctl.c:86
static char pid_file[MAXPGPATH]
Definition: pg_ctl.c:103
long pgpid_t
Definition: pg_ctl.c:39
#define stat(a, b)
Definition: win32_port.h:255
#define strerror
Definition: port.h:206
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
static char version_file[MAXPGPATH]
Definition: pg_ctl.c:102
#define _(x)
Definition: elog.c:88

◆ main()

int main ( int  argc,
char **  argv 
)

Definition at line 2260 of file pg_ctl.c.

References _, adjust_data_dir(), allow_core_files, argv0, backup_file, canonicalize_path(), ctl_command, do_advice(), do_help(), do_init(), do_kill(), do_logrotate(), do_promote(), do_reload(), do_restart(), do_start(), do_status(), do_stop(), do_wait, event_source, exec_path, free, get_progname(), GetDataDirectoryCreatePerm(), getopt_long(), INIT_COMMAND, KILL_COMMAND, log_file, LOGROTATE_COMMAND, MAXPGPATH, no_argument, NO_COMMAND, optarg, optind, pg_config, pg_data, pg_logging_init(), pg_mode_mask, PG_MODE_MASK_OWNER, pg_strdup(), PG_TEXTDOMAIN, pgdata_opt, pid_file, post_opts, postopts_file, progname, PROMOTE_COMMAND, psprintf(), putenv, REGISTER_COMMAND, register_password, register_servicename, register_username, RELOAD_COMMAND, required_argument, RESTART_COMMAND, RUN_AS_SERVICE_COMMAND, set_mode(), set_pglocale_pgservice(), set_sig(), sig, SIGHUP, silent_mode, snprintf, START_COMMAND, start_time, STATUS_COMMAND, STOP_COMMAND, UNREGISTER_COMMAND, version_file, wait_seconds, wait_seconds_arg, and write_stderr().

2261 {
2262  static struct option long_options[] = {
2263  {"help", no_argument, NULL, '?'},
2264  {"version", no_argument, NULL, 'V'},
2265  {"log", required_argument, NULL, 'l'},
2266  {"mode", required_argument, NULL, 'm'},
2267  {"pgdata", required_argument, NULL, 'D'},
2268  {"options", required_argument, NULL, 'o'},
2269  {"silent", no_argument, NULL, 's'},
2270  {"timeout", required_argument, NULL, 't'},
2271  {"core-files", no_argument, NULL, 'c'},
2272  {"wait", no_argument, NULL, 'w'},
2273  {"no-wait", no_argument, NULL, 'W'},
2274  {NULL, 0, NULL, 0}
2275  };
2276 
2277  char *env_wait;
2278  int option_index;
2279  int c;
2280  pgpid_t killproc = 0;
2281 
2282  pg_logging_init(argv[0]);
2283  progname = get_progname(argv[0]);
2284  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_ctl"));
2285  start_time = time(NULL);
2286 
2287  /*
2288  * save argv[0] so do_start() can look for the postmaster if necessary. we
2289  * don't look for postmaster here because in many cases we won't need it.
2290  */
2291  argv0 = argv[0];
2292 
2293  /* Set restrictive mode mask until PGDATA permissions are checked */
2294  umask(PG_MODE_MASK_OWNER);
2295 
2296  /* support --help and --version even if invoked as root */
2297  if (argc > 1)
2298  {
2299  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2300  {
2301  do_help();
2302  exit(0);
2303  }
2304  else if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2305  {
2306  puts("pg_ctl (PostgreSQL) " PG_VERSION);
2307  exit(0);
2308  }
2309  }
2310 
2311  /*
2312  * Disallow running as root, to forestall any possible security holes.
2313  */
2314 #ifndef WIN32
2315  if (geteuid() == 0)
2316  {
2317  write_stderr(_("%s: cannot be run as root\n"
2318  "Please log in (using, e.g., \"su\") as the "
2319  "(unprivileged) user that will\n"
2320  "own the server process.\n"),
2321  progname);
2322  exit(1);
2323  }
2324 #endif
2325 
2326  env_wait = getenv("PGCTLTIMEOUT");
2327  if (env_wait != NULL)
2328  wait_seconds = atoi(env_wait);
2329 
2330  /*
2331  * 'Action' can be before or after args so loop over both. Some
2332  * getopt_long() implementations will reorder argv[] to place all flags
2333  * first (GNU?), but we don't rely on it. Our /port version doesn't do
2334  * that.
2335  */
2336  optind = 1;
2337 
2338  /* process command-line options */
2339  while (optind < argc)
2340  {
2341  while ((c = getopt_long(argc, argv, "cD:e:l:m:N:o:p:P:sS:t:U:wW",
2342  long_options, &option_index)) != -1)
2343  {
2344  switch (c)
2345  {
2346  case 'D':
2347  {
2348  char *pgdata_D;
2349  char *env_var;
2350 
2351  pgdata_D = pg_strdup(optarg);
2352  canonicalize_path(pgdata_D);
2353  env_var = psprintf("PGDATA=%s", pgdata_D);
2354  putenv(env_var);
2355 
2356  /*
2357  * We could pass PGDATA just in an environment
2358  * variable but we do -D too for clearer postmaster
2359  * 'ps' display
2360  */
2361  pgdata_opt = psprintf("-D \"%s\" ", pgdata_D);
2362  break;
2363  }
2364  case 'e':
2366  break;
2367  case 'l':
2369  break;
2370  case 'm':
2371  set_mode(optarg);
2372  break;
2373  case 'N':
2375  break;
2376  case 'o':
2377  /* append option? */
2378  if (!post_opts)
2380  else
2381  {
2382  char *old_post_opts = post_opts;
2383 
2384  post_opts = psprintf("%s %s", old_post_opts, optarg);
2385  free(old_post_opts);
2386  }
2387  break;
2388  case 'p':
2390  break;
2391  case 'P':
2393  break;
2394  case 's':
2395  silent_mode = true;
2396  break;
2397  case 'S':
2398 #ifdef WIN32
2399  set_starttype(optarg);
2400 #else
2401  write_stderr(_("%s: -S option not supported on this platform\n"),
2402  progname);
2403  exit(1);
2404 #endif
2405  break;
2406  case 't':
2407  wait_seconds = atoi(optarg);
2408  wait_seconds_arg = true;
2409  break;
2410  case 'U':
2411  if (strchr(optarg, '\\'))
2413  else
2414  /* Prepend .\ for local accounts */
2415  register_username = psprintf(".\\%s", optarg);
2416  break;
2417  case 'w':
2418  do_wait = true;
2419  break;
2420  case 'W':
2421  do_wait = false;
2422  break;
2423  case 'c':
2424  allow_core_files = true;
2425  break;
2426  default:
2427  /* getopt_long already issued a suitable error message */
2428  do_advice();
2429  exit(1);
2430  }
2431  }
2432 
2433  /* Process an action */
2434  if (optind < argc)
2435  {
2436  if (ctl_command != NO_COMMAND)
2437  {
2438  write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
2439  do_advice();
2440  exit(1);
2441  }
2442 
2443  if (strcmp(argv[optind], "init") == 0
2444  || strcmp(argv[optind], "initdb") == 0)
2446  else if (strcmp(argv[optind], "start") == 0)
2448  else if (strcmp(argv[optind], "stop") == 0)
2450  else if (strcmp(argv[optind], "restart") == 0)
2452  else if (strcmp(argv[optind], "reload") == 0)
2454  else if (strcmp(argv[optind], "status") == 0)
2456  else if (strcmp(argv[optind], "promote") == 0)
2458  else if (strcmp(argv[optind], "logrotate") == 0)
2460  else if (strcmp(argv[optind], "kill") == 0)
2461  {
2462  if (argc - optind < 3)
2463  {
2464  write_stderr(_("%s: missing arguments for kill mode\n"), progname);
2465  do_advice();
2466  exit(1);
2467  }
2469  set_sig(argv[++optind]);
2470  killproc = atol(argv[++optind]);
2471  }
2472 #ifdef WIN32
2473  else if (strcmp(argv[optind], "register") == 0)
2475  else if (strcmp(argv[optind], "unregister") == 0)
2477  else if (strcmp(argv[optind], "runservice") == 0)
2479 #endif
2480  else
2481  {
2482  write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
2483  do_advice();
2484  exit(1);
2485  }
2486  optind++;
2487  }
2488  }
2489 
2490  if (ctl_command == NO_COMMAND)
2491  {
2492  write_stderr(_("%s: no operation specified\n"), progname);
2493  do_advice();
2494  exit(1);
2495  }
2496 
2497  /* Note we put any -D switch into the env var above */
2498  pg_config = getenv("PGDATA");
2499  if (pg_config)
2500  {
2504  }
2505 
2506  /* -D might point at config-only directory; if so find the real PGDATA */
2507  adjust_data_dir();
2508 
2509  /* Complain if -D needed and not provided */
2510  if (pg_config == NULL &&
2512  {
2513  write_stderr(_("%s: no database directory specified and environment variable PGDATA unset\n"),
2514  progname);
2515  do_advice();
2516  exit(1);
2517  }
2518 
2519  if (ctl_command == RELOAD_COMMAND)
2520  {
2521  sig = SIGHUP;
2522  do_wait = false;
2523  }
2524 
2525  if (pg_data)
2526  {
2527  snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
2528  snprintf(version_file, MAXPGPATH, "%s/PG_VERSION", pg_data);
2529  snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
2530  snprintf(backup_file, MAXPGPATH, "%s/backup_label", pg_data);
2531 
2532  /*
2533  * Set mask based on PGDATA permissions,
2534  *
2535  * Don't error here if the data directory cannot be stat'd. This is
2536  * handled differently based on the command and we don't want to
2537  * interfere with that logic.
2538  */
2540  umask(pg_mode_mask);
2541  }
2542 
2543  switch (ctl_command)
2544  {
2545  case INIT_COMMAND:
2546  do_init();
2547  break;
2548  case STATUS_COMMAND:
2549  do_status();
2550  break;
2551  case START_COMMAND:
2552  do_start();
2553  break;
2554  case STOP_COMMAND:
2555  do_stop();
2556  break;
2557  case RESTART_COMMAND:
2558  do_restart();
2559  break;
2560  case RELOAD_COMMAND:
2561  do_reload();
2562  break;
2563  case PROMOTE_COMMAND:
2564  do_promote();
2565  break;
2566  case LOGROTATE_COMMAND:
2567  do_logrotate();
2568  break;
2569  case KILL_COMMAND:
2570  do_kill(killproc);
2571  break;
2572 #ifdef WIN32
2573  case REGISTER_COMMAND:
2574  pgwin32_doRegister();
2575  break;
2576  case UNREGISTER_COMMAND:
2577  pgwin32_doUnregister();
2578  break;
2580  pgwin32_doRunAsService();
2581  break;
2582 #endif
2583  default:
2584  break;
2585  }
2586 
2587  exit(0);
2588 }
static char * argv0
Definition: pg_ctl.c:97
static int wait_seconds
Definition: pg_ctl.c:80
const char * get_progname(const char *argv0)
Definition: path.c:453
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
static char * log_file
Definition: pg_ctl.c:91
void pg_logging_init(const char *argv0)
Definition: logging.c:76
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static void do_help(void)
Definition: pg_ctl.c:2031
static char * post_opts
Definition: pg_ctl.c:89
static void do_stop(void)
Definition: pg_ctl.c:951
void canonicalize_path(char *path)
Definition: path.c:254
static void adjust_data_dir(void)
Definition: pg_ctl.c:2183
static char * pg_data
Definition: pg_ctl.c:86
static time_t start_time
Definition: pg_ctl.c:99
static char * register_password
Definition: pg_ctl.c:96
#define required_argument
Definition: getopt_long.h:25
int optind
Definition: getopt.c:50
static void do_logrotate(void)
Definition: pg_ctl.c:1268
static char pid_file[MAXPGPATH]
Definition: pg_ctl.c:103
long pgpid_t
Definition: pg_ctl.c:39
static char backup_file[MAXPGPATH]
Definition: pg_ctl.c:104
#define MAXPGPATH
static char * register_username
Definition: pg_ctl.c:95
static char * register_servicename
Definition: pg_ctl.c:94
char * c
static void do_start(void)
Definition: pg_ctl.c:858
#define SIGHUP
Definition: win32_port.h:153
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static void do_kill(pgpid_t pid)
Definition: pg_ctl.c:1406
static void do_restart(void)
Definition: pg_ctl.c:1038
static void do_status(void)
Definition: pg_ctl.c:1349
#define no_argument
Definition: getopt_long.h:24
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1178
static char * pgdata_opt
Definition: pg_ctl.c:88
#define PG_MODE_MASK_OWNER
Definition: file_perm.h:24
static char postopts_file[MAXPGPATH]
Definition: pg_ctl.c:101
static int sig
Definition: pg_ctl.c:84
#define free(a)
Definition: header.h:65
static void do_promote(void)
Definition: pg_ctl.c:1169
static bool allow_core_files
Definition: pg_ctl.c:98
static char * exec_path
Definition: pg_ctl.c:92
static void do_init(void)
Definition: pg_ctl.c:830
#define putenv(x)
Definition: win32_port.h:474
static char * event_source
Definition: pg_ctl.c:93
static const char * progname
Definition: pg_ctl.c:90
static bool wait_seconds_arg
Definition: pg_ctl.c:81
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
bool GetDataDirectoryCreatePerm(const char *dataDir)
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:434
static bool do_wait
Definition: pg_ctl.c:79
static void set_mode(char *modeopt)
Definition: pg_ctl.c:2105
static void do_reload(void)
Definition: pg_ctl.c:1132
char * optarg
Definition: getopt.c:52
static void static void do_advice(void)
Definition: pg_ctl.c:2023
static char version_file[MAXPGPATH]
Definition: pg_ctl.c:102
#define snprintf
Definition: port.h:193
static CtlCommand ctl_command
Definition: pg_ctl.c:85
#define _(x)
Definition: elog.c:88
int pg_mode_mask
Definition: file_perm.c:25
static void set_sig(char *signame)
Definition: pg_ctl.c:2133
static bool silent_mode
Definition: pg_ctl.c:82
static char * pg_config
Definition: pg_ctl.c:87

◆ postmaster_is_alive()

static bool postmaster_is_alive ( pid_t  pid)
static

Definition at line 1325 of file pg_ctl.c.

References kill.

Referenced by do_restart(), and do_status().

1326 {
1327  /*
1328  * Test to see if the process is still there. Note that we do not
1329  * consider an EPERM failure to mean that the process is still there;
1330  * EPERM must mean that the given PID belongs to some other userid, and
1331  * considering the permissions on $PGDATA, that means it's not the
1332  * postmaster we are after.
1333  *
1334  * Don't believe that our own PID or parent shell's PID is the postmaster,
1335  * either. (Windows hasn't got getppid(), though.)
1336  */
1337  if (pid == getpid())
1338  return false;
1339 #ifndef WIN32
1340  if (pid == getppid())
1341  return false;
1342 #endif
1343  if (kill(pid, 0) == 0)
1344  return true;
1345  return false;
1346 }
#define kill(pid, sig)
Definition: win32_port.h:426

◆ print_msg()

static void print_msg ( const char *  msg)
static

Definition at line 239 of file pg_ctl.c.

References silent_mode, and generate_unaccent_rules::stdout.

Referenced by do_logrotate(), do_promote(), do_reload(), do_restart(), do_start(), do_stop(), and wait_for_postmaster().

240 {
241  if (!silent_mode)
242  {
243  fputs(msg, stdout);
244  fflush(stdout);
245  }
246 }
static bool silent_mode
Definition: pg_ctl.c:82

◆ read_post_opts()

static void read_post_opts ( void  )
static

Definition at line 725 of file pg_ctl.c.

References _, ctl_command, exec_path, free_readfile(), pg_strdup(), post_opts, postopts_file, progname, readfile(), RESTART_COMMAND, and write_stderr().

Referenced by do_kill(), and do_start().

726 {
727  if (post_opts == NULL)
728  {
729  post_opts = ""; /* default */
731  {
732  char **optlines;
733  int numlines;
734 
735  optlines = readfile(postopts_file, &numlines);
736  if (optlines == NULL)
737  {
738  write_stderr(_("%s: could not read file \"%s\"\n"), progname, postopts_file);
739  exit(1);
740  }
741  else if (numlines != 1)
742  {
743  write_stderr(_("%s: option file \"%s\" must have exactly one line\n"),
745  exit(1);
746  }
747  else
748  {
749  char *optline;
750  char *arg1;
751 
752  optline = optlines[0];
753 
754  /*
755  * Are we at the first option, as defined by space and
756  * double-quote?
757  */
758  if ((arg1 = strstr(optline, " \"")) != NULL)
759  {
760  *arg1 = '\0'; /* terminate so we get only program name */
761  post_opts = pg_strdup(arg1 + 1); /* point past whitespace */
762  }
763  if (exec_path == NULL)
764  exec_path = pg_strdup(optline);
765  }
766 
767  /* Free the results of readfile. */
768  free_readfile(optlines);
769  }
770  }
771 }
static char * post_opts
Definition: pg_ctl.c:89
static char ** readfile(const char *path, int *numlines)
Definition: pg_ctl.c:317
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static char postopts_file[MAXPGPATH]
Definition: pg_ctl.c:101
static void free_readfile(char **optlines)
Definition: pg_ctl.c:413
static char * exec_path
Definition: pg_ctl.c:92
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
static CtlCommand ctl_command
Definition: pg_ctl.c:85
#define _(x)
Definition: elog.c:88

◆ readfile()

static char ** readfile ( const char *  path,
int *  numlines 
)
static

Definition at line 317 of file pg_ctl.c.

References close, fd(), free, i, PG_BINARY, pg_malloc(), read, and stat.

Referenced by do_status(), read_post_opts(), and wait_for_postmaster().

318 {
319  int fd;
320  int nlines;
321  char **result;
322  char *buffer;
323  char *linebegin;
324  int i;
325  int n;
326  int len;
327  struct stat statbuf;
328 
329  *numlines = 0; /* in case of failure or empty file */
330 
331  /*
332  * Slurp the file into memory.
333  *
334  * The file can change concurrently, so we read the whole file into memory
335  * with a single read() call. That's not guaranteed to get an atomic
336  * snapshot, but in practice, for a small file, it's close enough for the
337  * current use.
338  */
339  fd = open(path, O_RDONLY | PG_BINARY, 0);
340  if (fd < 0)
341  return NULL;
342  if (fstat(fd, &statbuf) < 0)
343  {
344  close(fd);
345  return NULL;
346  }
347  if (statbuf.st_size == 0)
348  {
349  /* empty file */
350  close(fd);
351  result = (char **) pg_malloc(sizeof(char *));
352  *result = NULL;
353  return result;
354  }
355  buffer = pg_malloc(statbuf.st_size + 1);
356 
357  len = read(fd, buffer, statbuf.st_size + 1);
358  close(fd);
359  if (len != statbuf.st_size)
360  {
361  /* oops, the file size changed between fstat and read */
362  free(buffer);
363  return NULL;
364  }
365 
366  /*
367  * Count newlines. We expect there to be a newline after each full line,
368  * including one at the end of file. If there isn't a newline at the end,
369  * any characters after the last newline will be ignored.
370  */
371  nlines = 0;
372  for (i = 0; i < len; i++)
373  {
374  if (buffer[i] == '\n')
375  nlines++;
376  }
377 
378  /* set up the result buffer */
379  result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
380  *numlines = nlines;
381 
382  /* now split the buffer into lines */
383  linebegin = buffer;
384  n = 0;
385  for (i = 0; i < len; i++)
386  {
387  if (buffer[i] == '\n')
388  {
389  int slen = &buffer[i] - linebegin;
390  char *linebuf = pg_malloc(slen + 1);
391 
392  memcpy(linebuf, linebegin, slen);
393  /* we already dropped the \n, but get rid of any \r too */
394  if (slen > 0 && linebuf[slen - 1] == '\r')
395  slen--;
396  linebuf[slen] = '\0';
397  result[n++] = linebuf;
398  linebegin = &buffer[i + 1];
399  }
400  }
401  result[n] = NULL;
402 
403  free(buffer);
404 
405  return result;
406 }
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1234
#define stat(a, b)
Definition: win32_port.h:255
#define free(a)
Definition: header.h:65
int i
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13

◆ set_mode()

static void set_mode ( char *  modeopt)
static

Definition at line 2105 of file pg_ctl.c.

References _, do_advice(), FAST_MODE, IMMEDIATE_MODE, progname, shutdown_mode, sig, SIGQUIT, SMART_MODE, and write_stderr().

Referenced by main().

2106 {
2107  if (strcmp(modeopt, "s") == 0 || strcmp(modeopt, "smart") == 0)
2108  {
2110  sig = SIGTERM;
2111  }
2112  else if (strcmp(modeopt, "f") == 0 || strcmp(modeopt, "fast") == 0)
2113  {
2115  sig = SIGINT;
2116  }
2117  else if (strcmp(modeopt, "i") == 0 || strcmp(modeopt, "immediate") == 0)
2118  {
2120  sig = SIGQUIT;
2121  }
2122  else
2123  {
2124  write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname, modeopt);
2125  do_advice();
2126  exit(1);
2127  }
2128 }
#define SIGQUIT
Definition: win32_port.h:154
static ShutdownMode shutdown_mode
Definition: pg_ctl.c:83
static int sig
Definition: pg_ctl.c:84
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
static void static void do_advice(void)
Definition: pg_ctl.c:2023
#define _(x)
Definition: elog.c:88

◆ set_sig()

static void set_sig ( char *  signame)
static

Definition at line 2133 of file pg_ctl.c.

References _, do_advice(), progname, sig, SIGABRT, SIGHUP, SIGKILL, SIGQUIT, SIGUSR1, SIGUSR2, and write_stderr().

Referenced by main().

2134 {
2135  if (strcmp(signame, "HUP") == 0)
2136  sig = SIGHUP;
2137  else if (strcmp(signame, "INT") == 0)
2138  sig = SIGINT;
2139  else if (strcmp(signame, "QUIT") == 0)
2140  sig = SIGQUIT;
2141  else if (strcmp(signame, "ABRT") == 0)
2142  sig = SIGABRT;
2143  else if (strcmp(signame, "KILL") == 0)
2144  sig = SIGKILL;
2145  else if (strcmp(signame, "TERM") == 0)
2146  sig = SIGTERM;
2147  else if (strcmp(signame, "USR1") == 0)
2148  sig = SIGUSR1;
2149  else if (strcmp(signame, "USR2") == 0)
2150  sig = SIGUSR2;
2151  else
2152  {
2153  write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname, signame);
2154  do_advice();
2155  exit(1);
2156  }
2157 }
#define SIGQUIT
Definition: win32_port.h:154
#define SIGUSR1
Definition: win32_port.h:165
#define SIGUSR2
Definition: win32_port.h:166
#define SIGABRT
Definition: win32_port.h:156
#define SIGKILL
Definition: win32_port.h:157
#define SIGHUP
Definition: win32_port.h:153
static int sig
Definition: pg_ctl.c:84
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
static void static void do_advice(void)
Definition: pg_ctl.c:2023
#define _(x)
Definition: elog.c:88

◆ start_postmaster()

static pgpid_t start_postmaster ( void  )
static

Definition at line 443 of file pg_ctl.c.

References _, close, DEVNULL, exec_path, fd(), log_file, MAXPGPATH, pgdata_opt, post_opts, progname, snprintf, generate_unaccent_rules::stdout, strerror, and write_stderr().

Referenced by check_and_dump_old_cluster(), do_start(), issue_warnings_and_set_wal_level(), main(), and setup().

444 {
445  char cmd[MAXPGPATH];
446 
447 #ifndef WIN32
448  pgpid_t pm_pid;
449 
450  /* Flush stdio channels just before fork, to avoid double-output problems */
451  fflush(stdout);
452  fflush(stderr);
453 
454  pm_pid = fork();
455  if (pm_pid < 0)
456  {
457  /* fork failed */
458  write_stderr(_("%s: could not start server: %s\n"),
459  progname, strerror(errno));
460  exit(1);
461  }
462  if (pm_pid > 0)
463  {
464  /* fork succeeded, in parent */
465  return pm_pid;
466  }
467 
468  /* fork succeeded, in child */
469 
470  /*
471  * If possible, detach the postmaster process from the launching process
472  * group and make it a group leader, so that it doesn't get signaled along
473  * with the current group that launched it.
474  */
475 #ifdef HAVE_SETSID
476  if (setsid() < 0)
477  {
478  write_stderr(_("%s: could not start server due to setsid() failure: %s\n"),
479  progname, strerror(errno));
480  exit(1);
481  }
482 #endif
483 
484  /*
485  * Since there might be quotes to handle here, it is easier simply to pass
486  * everything to a shell to process them. Use exec so that the postmaster
487  * has the same PID as the current child process.
488  */
489  if (log_file != NULL)
490  snprintf(cmd, MAXPGPATH, "exec \"%s\" %s%s < \"%s\" >> \"%s\" 2>&1",
492  DEVNULL, log_file);
493  else
494  snprintf(cmd, MAXPGPATH, "exec \"%s\" %s%s < \"%s\" 2>&1",
496 
497  (void) execl("/bin/sh", "/bin/sh", "-c", cmd, (char *) NULL);
498 
499  /* exec failed */
500  write_stderr(_("%s: could not start server: %s\n"),
501  progname, strerror(errno));
502  exit(1);
503 
504  return 0; /* keep dumb compilers quiet */
505 
506 #else /* WIN32 */
507 
508  /*
509  * As with the Unix case, it's easiest to use the shell (CMD.EXE) to
510  * handle redirection etc. Unfortunately CMD.EXE lacks any equivalent of
511  * "exec", so we don't get to find out the postmaster's PID immediately.
512  */
513  PROCESS_INFORMATION pi;
514  const char *comspec;
515 
516  /* Find CMD.EXE location using COMSPEC, if it's set */
517  comspec = getenv("COMSPEC");
518  if (comspec == NULL)
519  comspec = "CMD";
520 
521  if (log_file != NULL)
522  {
523  /*
524  * First, open the log file if it exists. The idea is that if the
525  * file is still locked by a previous postmaster run, we'll wait until
526  * it comes free, instead of failing with ERROR_SHARING_VIOLATION.
527  * (It'd be better to open the file in a sharing-friendly mode, but we
528  * can't use CMD.EXE to do that, so work around it. Note that the
529  * previous postmaster will still have the file open for a short time
530  * after removing postmaster.pid.)
531  *
532  * If the log file doesn't exist, we *must not* create it here. If we
533  * were launched with higher privileges than the restricted process
534  * will have, the log file might end up with permissions settings that
535  * prevent the postmaster from writing on it.
536  */
537  int fd = open(log_file, O_RDWR, 0);
538 
539  if (fd == -1)
540  {
541  /*
542  * ENOENT is expectable since we didn't use O_CREAT. Otherwise
543  * complain. We could just fall through and let CMD.EXE report
544  * the problem, but its error reporting is pretty miserable.
545  */
546  if (errno != ENOENT)
547  {
548  write_stderr(_("%s: could not open log file \"%s\": %s\n"),
549  progname, log_file, strerror(errno));
550  exit(1);
551  }
552  }
553  else
554  close(fd);
555 
556  snprintf(cmd, MAXPGPATH, "\"%s\" /C \"\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1\"",
558  }
559  else
560  snprintf(cmd, MAXPGPATH, "\"%s\" /C \"\"%s\" %s%s < \"%s\" 2>&1\"",
561  comspec, exec_path, pgdata_opt, post_opts, DEVNULL);
562 
563  if (!CreateRestrictedProcess(cmd, &pi, false))
564  {
565  write_stderr(_("%s: could not start server: error code %lu\n"),
566  progname, (unsigned long) GetLastError());
567  exit(1);
568  }
569  /* Don't close command process handle here; caller must do so */
570  postmasterProcess = pi.hProcess;
571  CloseHandle(pi.hThread);
572  return pi.dwProcessId; /* Shell's PID, not postmaster's! */
573 #endif /* WIN32 */
574 }
static char * log_file
Definition: pg_ctl.c:91
static char * post_opts
Definition: pg_ctl.c:89
static int fd(const char *x, int i)
Definition: preproc-init.c:105
long pgpid_t
Definition: pg_ctl.c:39
#define MAXPGPATH
#define DEVNULL
Definition: port.h:124
static char * pgdata_opt
Definition: pg_ctl.c:88
#define strerror
Definition: port.h:206
static char * exec_path
Definition: pg_ctl.c:92
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
#define close(a)
Definition: win32.h:12
#define snprintf
Definition: port.h:193
#define _(x)
Definition: elog.c:88

◆ trap_sigint_during_startup()

static void trap_sigint_during_startup ( int  sig)
static

Definition at line 780 of file pg_ctl.c.

References _, kill, postmasterPID, pqsignal(), progname, SIG_DFL, strerror, and write_stderr().

Referenced by do_start().

781 {
782  if (postmasterPID != -1)
783  {
784  if (kill(postmasterPID, SIGINT) != 0)
785  write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"),
787  }
788 
789  /*
790  * Clear the signal handler, and send the signal again, to terminate the
791  * process as normal.
792  */
793  pqsignal(SIGINT, SIG_DFL);
794  raise(SIGINT);
795 }
#define kill(pid, sig)
Definition: win32_port.h:426
long pgpid_t
Definition: pg_ctl.c:39
static volatile pgpid_t postmasterPID
Definition: pg_ctl.c:108
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
#define SIG_DFL
Definition: win32_port.h:148
#define strerror
Definition: port.h:206
static const char * progname
Definition: pg_ctl.c:90
static void write_stderr(const char *fmt,...) pg_attribute_printf(1
Definition: pg_ctl.c:205
#define _(x)
Definition: elog.c:88

◆ wait_for_postmaster()

static WaitPMResult wait_for_postmaster ( pgpid_t  pm_pid,
bool  do_checkpoint 
)
static

Definition at line 593 of file pg_ctl.c.

References _, free_readfile(), i, LOCK_FILE_LINE_PID, LOCK_FILE_LINE_PM_STATUS, LOCK_FILE_LINE_START_TIME, pg_usleep(), pid_file, PM_STATUS_READY, PM_STATUS_STANDBY, POSTMASTER_FAILED, POSTMASTER_READY, POSTMASTER_STILL_STARTING, print_msg(), progname, readfile(), start_time, status(), USEC_PER_SEC, wait_seconds, WAITS_PER_SEC, and write_stderr().

Referenced by do_kill(), and do_start().

594 {
595  int i;
596 
597  for (i = 0; i < wait_seconds * WAITS_PER_SEC; i++)
598  {
599  char **optlines;
600  int numlines;
601 
602  /*
603  * Try to read the postmaster.pid file. If it's not valid, or if the
604  * status line isn't there yet, just keep waiting.
605  */
606  if ((optlines = readfile(pid_file, &numlines)) != NULL &&
607  numlines >= LOCK_FILE_LINE_PM_STATUS)
608  {
609  /* File is complete enough for us, parse it */
610  pgpid_t pmpid;
611  time_t pmstart;
612 
613  /*
614  * Make sanity checks. If it's for the wrong PID, or the recorded
615  * start time is before pg_ctl started, then either we are looking
616  * at the wrong data directory, or this is a pre-existing pidfile
617  * that hasn't (yet?) been overwritten by our child postmaster.
618  * Allow 2 seconds slop for possible cross-process clock skew.
619  */
620  pmpid = atol(optlines[LOCK_FILE_LINE_PID - 1]);
621  pmstart = atol(optlines[LOCK_FILE_LINE_START_TIME - 1]);
622  if (pmstart >= start_time - 2 &&
623 #ifndef WIN32
624  pmpid == pm_pid
625 #else
626  /* Windows can only reject standalone-backend PIDs */
627  pmpid > 0
628 #endif
629  )
630  {
631  /*
632  * OK, seems to be a valid pidfile from our child. Check the
633  * status line (this assumes a v10 or later server).
634  */
635  char *pmstatus = optlines[LOCK_FILE_LINE_PM_STATUS - 1];
636 
637  if (strcmp(pmstatus, PM_STATUS_READY) == 0 ||
638  strcmp(pmstatus, PM_STATUS_STANDBY) == 0)
639  {
640  /* postmaster is done starting up */
641  free_readfile(optlines);
642  return POSTMASTER_READY;
643  }
644  }
645  }
646 
647  /*
648  * Free the results of readfile.
649  *
650  * This is safe to call even if optlines is NULL.
651  */
652  free_readfile(optlines);
653 
654  /*
655  * Check whether the child postmaster process is still alive. This
656  * lets us exit early if the postmaster fails during startup.
657  *
658  * On Windows, we may be checking the postmaster's parent shell, but
659  * that's fine for this purpose.
660  */
661 #ifndef WIN32
662  {
663  int exitstatus;
664 
665  if (waitpid((pid_t) pm_pid, &exitstatus, WNOHANG) == (pid_t) pm_pid)
666  return POSTMASTER_FAILED;
667  }
668 #else
669  if (WaitForSingleObject(postmasterProcess, 0) == WAIT_OBJECT_0)
670  return POSTMASTER_FAILED;
671 #endif
672 
673  /* Startup still in process; wait, printing a dot once per second */
674  if (i % WAITS_PER_SEC == 0)
675  {
676 #ifdef WIN32
677  if (do_checkpoint)
678  {
679  /*
680  * Increment the wait hint by 6 secs (connection timeout +
681  * sleep). We must do this to indicate to the SCM that our
682  * startup time is changing, otherwise it'll usually send a
683  * stop signal after 20 seconds, despite incrementing the
684  * checkpoint counter.
685  */
686  status.dwWaitHint += 6000;
687  status.dwCheckPoint++;
688  SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
689  }
690  else
691 #endif
692  print_msg(".");
693  }
694 
695  pg_usleep(USEC_PER_SEC / WAITS_PER_SEC);
696  }
697 
698  /* out of patience; report that postmaster is still starting up */
700 }
#define LOCK_FILE_LINE_PID
Definition: pidfile.h:37
static int wait_seconds
Definition: pg_ctl.c:80
static char ** readfile(const char *path, int *numlines)
Definition: pg_ctl.c:317
#define LOCK_FILE_LINE_START_TIME
Definition: pidfile.h:39
static time_t start_time
Definition: pg_ctl.c:99
void pg_usleep(long microsec)
Definition: signal.c:53
static char pid_file[MAXPGPATH]
Definition: pg_ctl.c:103
long pgpid_t
Definition: pg_ctl.c:39
#define PM_STATUS_READY
Definition: pidfile.h:53
#define USEC_PER_SEC
Definition: pg_ctl.c:75
static void free_readfile(char **optlines)
Definition: pg_ctl.c:413
#define PM_STATUS_STANDBY
Definition: pidfile.h:54
int i
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
#define LOCK_FILE_LINE_PM_STATUS
Definition: pidfile.h:44
static void print_msg(const char *msg)
Definition: pg_ctl.c:239
#define WAITS_PER_SEC
Definition: pg_ctl.c:77

◆ write_stderr()

static void write_stderr ( const char *  fmt,
  ... 
)
static

Definition at line 205 of file pg_ctl.c.

References pgwin32_is_service(), vfprintf, and vsnprintf.

Referenced by adjust_data_dir(), do_advice(), do_init(), do_kill(), do_logrotate(), do_promote(), do_reload(), do_restart(), do_start(), do_stop(), find_other_exec_or_die(), get_control_dbstate(), get_pgpid(), main(), read_post_opts(), set_mode(), set_sig(), start_postmaster(), trap_sigint_during_startup(), and wait_for_postmaster().

206 {
207  va_list ap;
208 
209  va_start(ap, fmt);
210 #ifndef WIN32
211  /* On Unix, we just fprintf to stderr */
212  vfprintf(stderr, fmt, ap);
213 #else
214 
215  /*
216  * On Win32, we print to stderr if running on a console, or write to
217  * eventlog if running as a service
218  */
219  if (pgwin32_is_service()) /* Running as a service */
220  {
221  char errbuf[2048]; /* Arbitrary size? */
222 
223  vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
224 
225  write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
226  }
227  else
228  /* Not running as service, write to stderr */
229  vfprintf(stderr, fmt, ap);
230 #endif
231  va_end(ap);
232 }
#define vsnprintf
Definition: port.h:192
int pgwin32_is_service(void)
#define vfprintf
Definition: port.h:196

Variable Documentation

◆ allow_core_files

bool allow_core_files = false
static

Definition at line 98 of file pg_ctl.c.

Referenced by do_start(), and main().

◆ argv0

char* argv0 = NULL
static

Definition at line 97 of file pg_ctl.c.

Referenced by adjust_data_dir(), do_init(), do_kill(), do_start(), and main().

◆ backup_file

char backup_file[MAXPGPATH]
static

Definition at line 104 of file pg_ctl.c.

Referenced by do_restart(), do_stop(), and main().

◆ ctl_command

CtlCommand ctl_command = NO_COMMAND
static

Definition at line 85 of file pg_ctl.c.

Referenced by do_start(), main(), and read_post_opts().

◆ do_wait

bool do_wait = true
static

Definition at line 79 of file pg_ctl.c.

Referenced by do_kill(), do_promote(), do_start(), do_stop(), main(), and WaitForWorkers().

◆ event_source

char* event_source = NULL
static

Definition at line 93 of file pg_ctl.c.

Referenced by do_kill(), and main().

◆ exec_path

char* exec_path = NULL
static

◆ log_file

char* log_file = NULL
static

Definition at line 91 of file pg_ctl.c.

Referenced by main(), and start_postmaster().

◆ logrotate_file

char logrotate_file[MAXPGPATH]
static

Definition at line 106 of file pg_ctl.c.

Referenced by do_logrotate().

◆ pg_config

char* pg_config = NULL
static

Definition at line 87 of file pg_ctl.c.

Referenced by adjust_data_dir(), do_kill(), and main().

◆ pg_data

char* pg_data = NULL
static

Definition at line 86 of file pg_ctl.c.

Referenced by adjust_data_dir(), do_logrotate(), do_promote(), get_control_dbstate(), get_pgpid(), and main().

◆ pgdata_opt

char* pgdata_opt = NULL
static

Definition at line 88 of file pg_ctl.c.

Referenced by adjust_data_dir(), do_init(), do_start(), main(), and start_postmaster().

◆ pid_file

char pid_file[MAXPGPATH]
static

◆ post_opts

char* post_opts = NULL
static

Definition at line 89 of file pg_ctl.c.

Referenced by adjust_data_dir(), do_init(), do_kill(), main(), read_post_opts(), and start_postmaster().

◆ postmasterPID

volatile pgpid_t postmasterPID = -1
static

Definition at line 108 of file pg_ctl.c.

Referenced by do_kill(), do_start(), and trap_sigint_during_startup().

◆ postopts_file

char postopts_file[MAXPGPATH]
static

Definition at line 101 of file pg_ctl.c.

Referenced by do_status(), main(), and read_post_opts().

◆ progname

◆ promote_file

char promote_file[MAXPGPATH]
static

Definition at line 105 of file pg_ctl.c.

Referenced by do_promote(), and pg_promote().

◆ register_password

char* register_password = NULL
static

Definition at line 96 of file pg_ctl.c.

Referenced by do_kill(), and main().

◆ register_servicename

char* register_servicename = "PostgreSQL"
static

Definition at line 94 of file pg_ctl.c.

Referenced by do_kill(), and main().

◆ register_username

char* register_username = NULL
static

Definition at line 95 of file pg_ctl.c.

Referenced by do_kill(), and main().

◆ shutdown_mode

ShutdownMode shutdown_mode = FAST_MODE
static

Definition at line 83 of file pg_ctl.c.

Referenced by do_restart(), do_stop(), and set_mode().

◆ sig

◆ silent_mode

bool silent_mode = false
static

Definition at line 82 of file pg_ctl.c.

Referenced by do_init(), do_kill(), main(), and print_msg().

◆ start_time

◆ version_file

char version_file[MAXPGPATH]
static

Definition at line 102 of file pg_ctl.c.

Referenced by get_pgpid(), main(), and write_version_file().

◆ wait_seconds

int wait_seconds = DEFAULT_WAIT
static

◆ wait_seconds_arg

bool wait_seconds_arg = false
static

Definition at line 81 of file pg_ctl.c.

Referenced by do_kill(), and main().