1
/*-------------------------------------------------------------------------
3
* pg_ctl --- start/stops/restarts the PostgreSQL server
5
* Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
7
* $PostgreSQL: pgsql/src/bin/pg_ctl/pg_ctl.c,v 1.53.4.2 2005-05-04 22:35:22 tgl Exp $
9
*-------------------------------------------------------------------------
12
#include "postgres_fe.h"
17
#include <sys/types.h>
21
#include "libpq/pqsignal.h"
22
#include "getopt_long.h"
24
#if defined(__CYGWIN__)
25
#include <sys/cygwin.h>
27
/* Cygwin defines WIN32 in windows.h, but we don't want it. */
31
#ifndef HAVE_INT_OPTRESET
35
/* PID can be negative for standalone backend */
38
#define _(x) gettext((x))
40
#define WHITESPACE "\f\n\r\t\v" /* as defined by isspace() */
42
/* postmaster version ident string */
43
#define PM_VERSIONSTR "postmaster (PostgreSQL) " PG_VERSION "\n"
65
RUN_AS_SERVICE_COMMAND
69
static bool do_wait = false;
70
static bool wait_set = false;
71
static int wait_seconds = 60;
72
static bool silent_mode = false;
73
static ShutdownMode shutdown_mode = SMART_MODE;
74
static int sig = SIGTERM; /* default */
75
static CtlCommand ctl_command = NO_COMMAND;
76
static char *pg_data = NULL;
77
static char *pgdata_opt = NULL;
78
static char *post_opts = NULL;
79
static const char *progname;
80
static char *log_file = NULL;
81
static char *postgres_path = NULL;
82
static char *register_servicename = "PostgreSQL"; /* FIXME: + version ID? */
83
static char *register_username = NULL;
84
static char *register_password = NULL;
85
static char *argv0 = NULL;
88
write_stderr(const char *fmt,...)
89
/* This extension allows gcc to check the format string for consistency with
90
the supplied arguments. */
91
__attribute__((format(printf, 1, 2)));
92
static void *xmalloc(size_t size);
93
static char *xstrdup(const char *s);
94
static void do_advice(void);
95
static void do_help(void);
96
static void set_mode(char *modeopt);
97
static void set_sig(char *signame);
98
static void do_start(void);
99
static void do_stop(void);
100
static void do_restart(void);
101
static void do_reload(void);
102
static void do_status(void);
103
static void do_kill(pgpid_t pid);
104
static void print_msg(const char *msg);
106
#if defined(WIN32) || defined(__CYGWIN__)
107
static bool pgwin32_IsInstalled(SC_HANDLE);
108
static char *pgwin32_CommandLine(bool);
109
static void pgwin32_doRegister(void);
110
static void pgwin32_doUnregister(void);
111
static void pgwin32_SetServiceStatus(DWORD);
112
static void WINAPI pgwin32_ServiceHandler(DWORD);
113
static void WINAPI pgwin32_ServiceMain(DWORD, LPTSTR *);
114
static void pgwin32_doRunAsService(void);
116
static pgpid_t get_pgpid(void);
117
static char **readfile(const char *path);
118
static int start_postmaster(void);
119
static bool test_postmaster_connection(void);
120
static bool postmaster_is_alive(pid_t pid);
122
static char def_postopts_file[MAXPGPATH];
123
static char postopts_file[MAXPGPATH];
124
static char pid_file[MAXPGPATH];
125
static char conf_file[MAXPGPATH];
128
#if defined(WIN32) || defined(__CYGWIN__)
130
write_eventlog(int level, const char *line)
132
static HANDLE evtHandle = INVALID_HANDLE_VALUE;
134
if (evtHandle == INVALID_HANDLE_VALUE)
136
evtHandle = RegisterEventSource(NULL, "PostgreSQL");
137
if (evtHandle == NULL)
139
evtHandle = INVALID_HANDLE_VALUE;
144
ReportEvent(evtHandle,
147
0, /* All events are Id 0 */
157
* Write errors to stderr (or by equal means when stderr is
161
write_stderr(const char *fmt,...)
166
#if !defined(WIN32) && !defined(__CYGWIN__)
167
/* On Unix, we just fprintf to stderr */
168
vfprintf(stderr, fmt, ap);
172
* On Win32, we print to stderr if running on a console, or write to
173
* eventlog if running as a service
175
if (!isatty(fileno(stderr))) /* Running as a service */
177
char errbuf[2048]; /* Arbitrary size? */
179
vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
181
write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
184
/* Not running as service, write to stderr */
185
vfprintf(stderr, fmt, ap);
191
* routines to check memory allocations and fail noisily.
199
result = malloc(size);
202
write_stderr(_("%s: out of memory\n"), progname);
210
xstrdup(const char *s)
217
write_stderr(_("%s: out of memory\n"), progname);
224
* Given an already-localized string, print it to stdout unless the
225
* user has specified that no messages should be printed.
228
print_msg(const char *msg)
243
pidf = fopen(pid_file, "r");
246
/* No pid file, not an error on startup */
251
write_stderr(_("%s: could not open PID file \"%s\": %s\n"),
252
progname, pid_file, strerror(errno));
256
if (fscanf(pidf, "%ld", &pid) != 1)
258
write_stderr(_("%s: invalid data in PID file \"%s\"\n"),
263
return (pgpid_t) pid;
268
* get the lines from a text file - return NULL if file can't be opened
271
readfile(const char *path)
281
if ((infile = fopen(path, "r")) == NULL)
284
/* pass over the file twice - the first time to size the result */
286
while ((c = fgetc(infile)) != EOF)
292
if (linelen > maxlength)
298
/* handle last line without a terminating newline (yuck) */
301
if (linelen > maxlength)
304
/* set up the result and the line buffer */
305
result = (char **) xmalloc((nlines + 1) * sizeof(char *));
306
buffer = (char *) xmalloc(maxlength + 1);
308
/* now reprocess the file and store the lines */
311
while (fgets(buffer, maxlength + 1, infile) != NULL)
312
result[nlines++] = xstrdup(buffer);
315
result[nlines] = NULL;
323
* start/test/stop routines
327
start_postmaster(void)
330
* Since there might be quotes to handle here, it is easier simply to
331
* pass everything to a shell to process them.
336
* Win32 needs START /B rather than "&".
338
* Win32 has a problem with START and quoted executable names. You must
339
* add a "" as the title at the beginning so you can quote the
341
* http://www.winnetmag.com/Article/ArticleID/14589/14589.html
342
* http://dev.remotenetworktechnology.com/cmd/cmdfaq.htm
344
if (log_file != NULL)
345
#ifndef WIN32 /* Cygwin doesn't have START */
346
snprintf(cmd, MAXPGPATH, "%s\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1 &%s",
348
snprintf(cmd, MAXPGPATH, "%sSTART /B \"\" \"%s\" %s%s < \"%s\" >> \"%s\" 2>&1%s",
350
SYSTEMQUOTE, postgres_path, pgdata_opt, post_opts,
351
DEVNULL, log_file, SYSTEMQUOTE);
353
#ifndef WIN32 /* Cygwin doesn't have START */
354
snprintf(cmd, MAXPGPATH, "%s\"%s\" %s%s < \"%s\" 2>&1 &%s",
356
snprintf(cmd, MAXPGPATH, "%sSTART /B \"\" \"%s\" %s%s < \"%s\" 2>&1%s",
358
SYSTEMQUOTE, postgres_path, pgdata_opt, post_opts,
359
DEVNULL, SYSTEMQUOTE);
366
/* Find the pgport and try a connection */
368
test_postmaster_connection(void)
371
bool success = false;
379
for (p = post_opts; *p;)
381
/* advance past whitespace/quoting */
382
while (isspace((unsigned char) *p) || *p == '\'' || *p == '"')
385
if (strncmp(p, "-p", strlen("-p")) == 0)
388
/* advance past whitespace/quoting */
389
while (isspace((unsigned char) *p) || *p == '\'' || *p == '"')
391
StrNCpy(portstr, p, Min(strcspn(p, "\"'" WHITESPACE) + 1,
393
/* keep looking, maybe there is another -p */
395
/* Advance to next whitespace */
396
while (*p && !isspace((unsigned char) *p))
405
optlines = readfile(conf_file);
406
if (optlines != NULL)
408
for (; *optlines != NULL; optlines++)
412
while (isspace((unsigned char) *p))
414
if (strncmp(p, "port", strlen("port")) != 0)
417
while (isspace((unsigned char) *p))
422
while (isspace((unsigned char) *p))
424
StrNCpy(portstr, p, Min(strcspn(p, "#" WHITESPACE) + 1,
426
/* keep looking, maybe there is another */
432
if (!*portstr && getenv("PGPORT") != NULL)
433
StrNCpy(portstr, getenv("PGPORT"), sizeof(portstr));
437
snprintf(portstr, sizeof(portstr), "%d", DEF_PGPORT);
439
for (i = 0; i < wait_seconds; i++)
441
if ((conn = PQsetdbLogin(NULL, portstr, NULL, NULL,
442
"template1", NULL, NULL)) != NULL &&
443
(PQstatus(conn) == CONNECTION_OK ||
444
(strcmp(PQerrorMessage(conn),
445
PQnoPasswordSupplied) == 0)))
454
pg_usleep(1000000); /* 1 sec */
468
char *optline = NULL;
471
if (ctl_command != RESTART_COMMAND)
473
old_pid = get_pgpid();
475
write_stderr(_("%s: another postmaster may be running; "
476
"trying to start postmaster anyway\n"),
480
if (post_opts == NULL)
485
optlines = readfile(ctl_command == RESTART_COMMAND ?
486
postopts_file : def_postopts_file);
487
if (optlines == NULL)
489
if (ctl_command == START_COMMAND)
493
write_stderr(_("%s: could not read file \"%s\"\n"), progname, postopts_file);
497
else if (optlines[0] == NULL || optlines[1] != NULL)
499
write_stderr(_("%s: option file \"%s\" must have exactly one line\n"),
500
progname, ctl_command == RESTART_COMMAND ?
501
postopts_file : def_postopts_file);
506
optline = optlines[0];
507
len = strcspn(optline, "\r\n");
510
if (ctl_command == RESTART_COMMAND)
514
arg1 = strchr(optline, *SYSTEMQUOTE);
515
if (arg1 == NULL || arg1 == optline)
519
*(arg1 - 1) = '\0'; /* this should be a space */
522
if (postgres_path != NULL)
523
postgres_path = optline;
530
/* No -D or -D already added during server start */
531
if (ctl_command == RESTART_COMMAND || pgdata_opt == NULL)
534
if (postgres_path == NULL)
536
char *postmaster_path;
539
postmaster_path = xmalloc(MAXPGPATH);
541
if ((ret = find_other_exec(argv0, "postmaster", PM_VERSIONSTR,
542
postmaster_path)) < 0)
544
char full_path[MAXPGPATH];
546
if (find_my_exec(argv0, full_path) < 0)
547
StrNCpy(full_path, progname, MAXPGPATH);
550
write_stderr(_("The program \"postmaster\" is needed by %s "
551
"but was not found in the\n"
552
"same directory as \"%s\".\n"
553
"Check your installation.\n"),
554
progname, full_path);
556
write_stderr(_("The program \"postmaster\" was found by \"%s\"\n"
557
"but was not the same version as %s.\n"
558
"Check your installation.\n"),
559
full_path, progname);
562
postgres_path = postmaster_path;
565
exitcode = start_postmaster();
568
write_stderr(_("%s: could not start postmaster: exit code was %d\n"),
579
write_stderr(_("%s: could not start postmaster\n"
580
"Examine the log output.\n"),
588
print_msg(_("waiting for postmaster to start..."));
590
if (test_postmaster_connection() == false)
592
printf(_("could not start postmaster\n"));
597
print_msg(_(" done\n"));
598
print_msg(_("postmaster started\n"));
602
print_msg(_("postmaster starting\n"));
614
if (pid == 0) /* no pid file */
616
write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
617
write_stderr(_("Is postmaster running?\n"));
620
else if (pid < 0) /* standalone backend, not postmaster */
623
write_stderr(_("%s: cannot stop postmaster; "
624
"postgres is running (PID: %ld)\n"),
629
if (kill((pid_t) pid, sig) != 0)
631
write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
638
print_msg(_("postmaster shutting down\n"));
643
print_msg(_("waiting for postmaster to shut down..."));
645
for (cnt = 0; cnt < wait_seconds; cnt++)
647
if ((pid = get_pgpid()) != 0)
650
pg_usleep(1000000); /* 1 sec */
656
if (pid != 0) /* pid file still exists */
658
print_msg(_(" failed\n"));
660
write_stderr(_("%s: postmaster does not shut down\n"), progname);
663
print_msg(_(" done\n"));
665
printf(_("postmaster stopped\n"));
671
* restart/reload routines
682
if (pid == 0) /* no pid file */
684
write_stderr(_("%s: PID file \"%s\" does not exist\n"),
686
write_stderr(_("Is postmaster running?\n"));
687
write_stderr(_("starting postmaster anyway\n"));
691
else if (pid < 0) /* standalone backend, not postmaster */
694
if (postmaster_is_alive((pid_t) pid))
696
write_stderr(_("%s: cannot restart postmaster; "
697
"postgres is running (PID: %ld)\n"),
699
write_stderr(_("Please terminate postgres and try again.\n"));
704
if (postmaster_is_alive((pid_t) pid))
706
if (kill((pid_t) pid, sig) != 0)
708
write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
713
print_msg(_("waiting for postmaster to shut down..."));
715
/* always wait for restart */
717
for (cnt = 0; cnt < wait_seconds; cnt++)
719
if ((pid = get_pgpid()) != 0)
722
pg_usleep(1000000); /* 1 sec */
728
if (pid != 0) /* pid file still exists */
730
print_msg(_(" failed\n"));
732
write_stderr(_("%s: postmaster does not shut down\n"), progname);
736
print_msg(_(" done\n"));
737
printf(_("postmaster stopped\n"));
741
write_stderr(_("%s: old postmaster process (PID: %ld) seems to be gone\n"),
743
write_stderr(_("starting postmaster anyway\n"));
756
if (pid == 0) /* no pid file */
758
write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
759
write_stderr(_("Is postmaster running?\n"));
762
else if (pid < 0) /* standalone backend, not postmaster */
765
write_stderr(_("%s: cannot reload postmaster; "
766
"postgres is running (PID: %ld)\n"),
768
write_stderr(_("Please terminate postgres and try again.\n"));
772
if (kill((pid_t) pid, sig) != 0)
774
write_stderr(_("%s: could not send reload signal (PID: %ld): %s\n"),
775
progname, pid, strerror(errno));
779
print_msg(_("postmaster signaled\n"));
787
postmaster_is_alive(pid_t pid)
790
* Test to see if the process is still there. Note that we do not
791
* consider an EPERM failure to mean that the process is still there;
792
* EPERM must mean that the given PID belongs to some other userid,
793
* and considering the permissions on $PGDATA, that means it's not
794
* the postmaster we are after.
796
* Don't believe that our own PID or parent shell's PID is the postmaster,
797
* either. (Windows hasn't got getppid(), though.)
802
if (pid == getppid())
805
if (kill(pid, 0) == 0)
816
if (pid != 0) /* 0 means no pid file */
818
if (pid < 0) /* standalone backend */
821
if (postmaster_is_alive((pid_t) pid))
823
printf(_("%s: a standalone backend \"postgres\" is running (PID: %ld)\n"),
828
else /* postmaster */
830
if (postmaster_is_alive((pid_t) pid))
834
printf(_("%s: postmaster is running (PID: %ld)\n"),
837
optlines = readfile(postopts_file);
838
if (optlines != NULL)
839
for (; *optlines != NULL; optlines++)
840
fputs(*optlines, stdout);
845
printf(_("%s: neither postmaster nor postgres running\n"), progname);
854
if (kill((pid_t) pid, sig) != 0)
856
write_stderr(_("%s: could not send signal %d (PID: %ld): %s\n"),
857
progname, sig, pid, strerror(errno));
862
#if defined(WIN32) || defined(__CYGWIN__)
865
pgwin32_IsInstalled(SC_HANDLE hSCM)
867
SC_HANDLE hService = OpenService(hSCM, register_servicename, SERVICE_QUERY_CONFIG);
868
bool bResult = (hService != NULL);
871
CloseServiceHandle(hService);
876
pgwin32_CommandLine(bool registration)
878
static char cmdLine[MAXPGPATH];
886
ret = find_my_exec(argv0, cmdLine);
889
write_stderr(_("%s: could not find own program executable\n"), progname);
895
ret = find_other_exec(argv0, "postmaster", PM_VERSIONSTR, cmdLine);
898
write_stderr(_("%s: could not find postmaster program executable\n"), progname);
904
/* need to convert to windows path */
905
cygwin_conv_to_full_win32_path(cmdLine, buf);
906
strcpy(cmdLine, buf);
911
if (strcasecmp(cmdLine + strlen(cmdLine) - 4, ".exe"))
913
/* If commandline does not end in .exe, append it */
914
strcat(cmdLine, ".exe");
916
strcat(cmdLine, " runservice -N \"");
917
strcat(cmdLine, register_servicename);
918
strcat(cmdLine, "\"");
923
strcat(cmdLine, " -D \"");
924
strcat(cmdLine, pg_data);
925
strcat(cmdLine, "\"");
929
strcat(cmdLine, " -w");
933
strcat(cmdLine, " ");
935
strcat(cmdLine, " -o \"");
936
strcat(cmdLine, post_opts);
938
strcat(cmdLine, "\"");
945
pgwin32_doRegister(void)
948
SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
952
write_stderr(_("%s: could not open service manager\n"), progname);
955
if (pgwin32_IsInstalled(hSCM))
957
CloseServiceHandle(hSCM);
958
write_stderr(_("%s: service \"%s\" already registered\n"), progname, register_servicename);
962
if ((hService = CreateService(hSCM, register_servicename, register_servicename,
963
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
964
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
965
pgwin32_CommandLine(true),
966
NULL, NULL, "RPCSS\0", register_username, register_password)) == NULL)
968
CloseServiceHandle(hSCM);
969
write_stderr(_("%s: could not register service \"%s\": error code %d\n"), progname, register_servicename, (int) GetLastError());
972
CloseServiceHandle(hService);
973
CloseServiceHandle(hSCM);
977
pgwin32_doUnregister(void)
980
SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
984
write_stderr(_("%s: could not open service manager\n"), progname);
987
if (!pgwin32_IsInstalled(hSCM))
989
CloseServiceHandle(hSCM);
990
write_stderr(_("%s: service \"%s\" not registered\n"), progname, register_servicename);
994
if ((hService = OpenService(hSCM, register_servicename, DELETE)) == NULL)
996
CloseServiceHandle(hSCM);
997
write_stderr(_("%s: could not open service \"%s\": error code %d\n"), progname, register_servicename, (int) GetLastError());
1000
if (!DeleteService(hService))
1002
CloseServiceHandle(hService);
1003
CloseServiceHandle(hSCM);
1004
write_stderr(_("%s: could not unregister service \"%s\": error code %d\n"), progname, register_servicename, (int) GetLastError());
1007
CloseServiceHandle(hService);
1008
CloseServiceHandle(hSCM);
1012
static SERVICE_STATUS status;
1013
static SERVICE_STATUS_HANDLE hStatus = (SERVICE_STATUS_HANDLE) 0;
1014
static HANDLE shutdownHandles[2];
1015
static pid_t postmasterPID = -1;
1017
#define shutdownEvent shutdownHandles[0]
1018
#define postmasterProcess shutdownHandles[1]
1021
pgwin32_SetServiceStatus(DWORD currentState)
1023
status.dwCurrentState = currentState;
1024
SetServiceStatus(hStatus, (LPSERVICE_STATUS) & status);
1028
pgwin32_ServiceHandler(DWORD request)
1032
case SERVICE_CONTROL_STOP:
1033
case SERVICE_CONTROL_SHUTDOWN:
1036
* We only need a short wait hint here as it just needs to
1037
* wait for the next checkpoint. They occur every 5 seconds
1040
status.dwWaitHint = 10000;
1041
pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1042
SetEvent(shutdownEvent);
1045
case SERVICE_CONTROL_PAUSE:
1046
/* Win32 config reloading */
1047
status.dwWaitHint = 5000;
1048
kill(postmasterPID, SIGHUP);
1051
/* FIXME: These could be used to replace other signals etc */
1052
case SERVICE_CONTROL_CONTINUE:
1053
case SERVICE_CONTROL_INTERROGATE:
1060
pgwin32_ServiceMain(DWORD argc, LPTSTR * argv)
1063
PROCESS_INFORMATION pi;
1066
/* Initialize variables */
1067
status.dwWin32ExitCode = S_OK;
1068
status.dwCheckPoint = 0;
1069
status.dwWaitHint = 60000;
1070
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1071
status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
1072
status.dwServiceSpecificExitCode = 0;
1073
status.dwCurrentState = SERVICE_START_PENDING;
1075
memset(&pi, 0, sizeof(pi));
1076
memset(&si, 0, sizeof(si));
1079
/* Register the control request handler */
1080
if ((hStatus = RegisterServiceCtrlHandler(register_servicename, pgwin32_ServiceHandler)) == (SERVICE_STATUS_HANDLE) 0)
1083
if ((shutdownEvent = CreateEvent(NULL, true, false, NULL)) == NULL)
1086
/* Start the postmaster */
1087
pgwin32_SetServiceStatus(SERVICE_START_PENDING);
1088
if (!CreateProcess(NULL, pgwin32_CommandLine(false), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
1090
pgwin32_SetServiceStatus(SERVICE_STOPPED);
1093
postmasterPID = pi.dwProcessId;
1094
postmasterProcess = pi.hProcess;
1095
CloseHandle(pi.hThread);
1096
pgwin32_SetServiceStatus(SERVICE_RUNNING);
1098
/* Wait for quit... */
1099
ret = WaitForMultipleObjects(2, shutdownHandles, FALSE, INFINITE);
1100
pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1103
case WAIT_OBJECT_0: /* shutdown event */
1104
kill(postmasterPID, SIGINT);
1107
* Increment the checkpoint and try again Abort after 12
1108
* checkpoints as the postmaster has probably hung
1110
while (WaitForSingleObject(postmasterProcess, 5000) == WAIT_TIMEOUT && status.dwCheckPoint < 12)
1111
status.dwCheckPoint++;
1114
case (WAIT_OBJECT_0 + 1): /* postmaster went down */
1118
/* shouldn't get here? */
1122
CloseHandle(shutdownEvent);
1123
CloseHandle(postmasterProcess);
1125
pgwin32_SetServiceStatus(SERVICE_STOPPED);
1129
pgwin32_doRunAsService(void)
1131
SERVICE_TABLE_ENTRY st[] = {{register_servicename, pgwin32_ServiceMain},
1134
if (StartServiceCtrlDispatcher(st) == 0)
1136
write_stderr(_("%s: could not start service \"%s\": error code %d\n"), progname, register_servicename, (int) GetLastError());
1145
write_stderr(_("Try \"%s --help\" for more information.\n"), progname);
1153
printf(_("%s is a utility to start, stop, restart, reload configuration files,\n"
1154
"report the status of a PostgreSQL server, or signal a PostgreSQL process.\n\n"), progname);
1155
printf(_("Usage:\n"));
1156
printf(_(" %s start [-w] [-D DATADIR] [-s] [-l FILENAME] [-o \"OPTIONS\"]\n"), progname);
1157
printf(_(" %s stop [-W] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"), progname);
1158
printf(_(" %s restart [-w] [-D DATADIR] [-s] [-m SHUTDOWN-MODE] [-o \"OPTIONS\"]\n"), progname);
1159
printf(_(" %s reload [-D DATADIR] [-s]\n"), progname);
1160
printf(_(" %s status [-D DATADIR]\n"), progname);
1161
printf(_(" %s kill SIGNALNAME PID\n"), progname);
1162
#if defined(WIN32) || defined(__CYGWIN__)
1163
printf(_(" %s register [-N SERVICENAME] [-U USERNAME] [-P PASSWORD] [-D DATADIR]\n"
1164
" [-w] [-o \"OPTIONS\"]\n"), progname);
1165
printf(_(" %s unregister [-N SERVICENAME]\n"), progname);
1168
printf(_("\nCommon options:\n"));
1169
printf(_(" -D, --pgdata DATADIR location of the database storage area\n"));
1170
printf(_(" -s, --silent only print errors, no informational messages\n"));
1171
printf(_(" -w wait until operation completes\n"));
1172
printf(_(" -W do not wait until operation completes\n"));
1173
printf(_(" --help show this help, then exit\n"));
1174
printf(_(" --version output version information, then exit\n"));
1175
printf(_("(The default is to wait for shutdown, but not for start or restart.)\n\n"));
1176
printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
1178
printf(_("\nOptions for start or restart:\n"));
1179
printf(_(" -l, --log FILENAME write (or append) server log to FILENAME\n"));
1180
printf(_(" -o OPTIONS command line options to pass to the postmaster\n"
1181
" (PostgreSQL server executable)\n"));
1182
printf(_(" -p PATH-TO-POSTMASTER normally not necessary\n"));
1184
printf(_("\nOptions for stop or restart:\n"));
1185
printf(_(" -m SHUTDOWN-MODE may be \"smart\", \"fast\", or \"immediate\"\n"));
1187
printf(_("\nShutdown modes are:\n"));
1188
printf(_(" smart quit after all clients have disconnected\n"));
1189
printf(_(" fast quit directly, with proper shutdown\n"));
1190
printf(_(" immediate quit without complete shutdown; will lead to recovery on restart\n"));
1192
printf(_("\nAllowed signal names for kill:\n"));
1193
printf(" HUP INT QUIT ABRT TERM USR1 USR2\n");
1195
#if defined(WIN32) || defined(__CYGWIN__)
1196
printf(_("\nOptions for register and unregister:\n"));
1197
printf(_(" -N SERVICENAME service name with which to register PostgreSQL server\n"));
1198
printf(_(" -P PASSWORD password of account to register PostgreSQL server\n"));
1199
printf(_(" -U USERNAME user name of account to register PostgreSQL server\n"));
1202
printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
1208
set_mode(char *modeopt)
1210
if (strcmp(modeopt, "s") == 0 || strcmp(modeopt, "smart") == 0)
1212
shutdown_mode = SMART_MODE;
1215
else if (strcmp(modeopt, "f") == 0 || strcmp(modeopt, "fast") == 0)
1217
shutdown_mode = FAST_MODE;
1220
else if (strcmp(modeopt, "i") == 0 || strcmp(modeopt, "immediate") == 0)
1222
shutdown_mode = IMMEDIATE_MODE;
1227
write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname, modeopt);
1236
set_sig(char *signame)
1238
if (!strcmp(signame, "HUP"))
1240
else if (!strcmp(signame, "INT"))
1242
else if (!strcmp(signame, "QUIT"))
1244
else if (!strcmp(signame, "ABRT"))
1248
* probably should NOT provide SIGKILL
1250
* else if (!strcmp(signame,"KILL")) sig = SIGKILL;
1252
else if (!strcmp(signame, "TERM"))
1254
else if (!strcmp(signame, "USR1"))
1256
else if (!strcmp(signame, "USR2"))
1260
write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname, signame);
1270
main(int argc, char **argv)
1272
static struct option long_options[] = {
1273
{"help", no_argument, NULL, '?'},
1274
{"version", no_argument, NULL, 'V'},
1275
{"log", required_argument, NULL, 'l'},
1276
{"mode", required_argument, NULL, 'm'},
1277
{"pgdata", required_argument, NULL, 'D'},
1278
{"silent", no_argument, NULL, 's'},
1284
pgpid_t killproc = 0;
1286
#if defined(WIN32) || defined(__CYGWIN__)
1287
setvbuf(stderr, NULL, _IONBF, 0);
1290
progname = get_progname(argv[0]);
1291
set_pglocale_pgservice(argv[0], "pg_ctl");
1294
* save argv[0] so do_start() can look for the postmaster if
1295
* necessary. we don't look for postmaster here because in many cases
1302
/* support --help and --version even if invoked as root */
1305
if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0 ||
1306
strcmp(argv[1], "-?") == 0)
1311
else if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0)
1313
printf("%s (PostgreSQL) %s\n", progname, PG_VERSION);
1319
* Disallow running as root, to forestall any possible security holes.
1322
#ifndef __BEOS__ /* no root check on BEOS */
1325
write_stderr(_("%s: cannot be run as root\n"
1326
"Please log in (using, e.g., \"su\") as the "
1327
"(unprivileged) user that will\n"
1328
"own the server process.\n"),
1336
* 'Action' can be before or after args so loop over both. Some
1337
* getopt_long() implementations will reorder argv[] to place all
1338
* flags first (GNU?), but we don't rely on it. Our /port version
1343
/* process command-line options */
1344
while (optind < argc)
1346
while ((c = getopt_long(argc, argv, "D:l:m:N:o:p:P:sU:wW", long_options, &option_index)) != -1)
1353
char *env_var = xmalloc(strlen(optarg) + 8);
1355
pgdata_D = xstrdup(optarg);
1356
canonicalize_path(pgdata_D);
1357
snprintf(env_var, strlen(optarg) + 8, "PGDATA=%s",
1362
* We could pass PGDATA just in an environment
1363
* variable but we do -D too for clearer
1364
* postmaster 'ps' display
1366
pgdata_opt = xmalloc(strlen(pgdata_D) + 7);
1367
snprintf(pgdata_opt, strlen(pgdata_D) + 7,
1373
log_file = xstrdup(optarg);
1379
register_servicename = xstrdup(optarg);
1382
post_opts = xstrdup(optarg);
1385
postgres_path = xstrdup(optarg);
1388
register_password = xstrdup(optarg);
1394
if (strchr(optarg, '\\'))
1395
register_username = xstrdup(optarg);
1397
/* Prepend .\ for local accounts */
1399
register_username = malloc(strlen(optarg) + 3);
1400
if (!register_username)
1402
write_stderr(_("%s: out of memory\n"), progname);
1405
strcpy(register_username, ".\\");
1406
strcat(register_username, optarg);
1418
write_stderr(_("%s: invalid option %s\n"), progname, optarg);
1424
/* Process an action */
1427
if (ctl_command != NO_COMMAND)
1429
write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
1434
if (strcmp(argv[optind], "start") == 0)
1435
ctl_command = START_COMMAND;
1436
else if (strcmp(argv[optind], "stop") == 0)
1437
ctl_command = STOP_COMMAND;
1438
else if (strcmp(argv[optind], "restart") == 0)
1439
ctl_command = RESTART_COMMAND;
1440
else if (strcmp(argv[optind], "reload") == 0)
1441
ctl_command = RELOAD_COMMAND;
1442
else if (strcmp(argv[optind], "status") == 0)
1443
ctl_command = STATUS_COMMAND;
1444
else if (strcmp(argv[optind], "kill") == 0)
1446
if (argc - optind < 3)
1448
write_stderr(_("%s: missing arguments for kill mode\n"), progname);
1452
ctl_command = KILL_COMMAND;
1453
set_sig(argv[++optind]);
1454
killproc = atol(argv[++optind]);
1456
#if defined(WIN32) || defined(__CYGWIN__)
1457
else if (strcmp(argv[optind], "register") == 0)
1458
ctl_command = REGISTER_COMMAND;
1459
else if (strcmp(argv[optind], "unregister") == 0)
1460
ctl_command = UNREGISTER_COMMAND;
1461
else if (strcmp(argv[optind], "runservice") == 0)
1462
ctl_command = RUN_AS_SERVICE_COMMAND;
1466
write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
1474
if (ctl_command == NO_COMMAND)
1476
write_stderr(_("%s: no operation specified\n"), progname);
1481
/* Note we put any -D switch into the env var above */
1482
pg_data = getenv("PGDATA");
1485
pg_data = xstrdup(pg_data);
1486
canonicalize_path(pg_data);
1489
if (pg_data == NULL &&
1490
ctl_command != KILL_COMMAND && ctl_command != UNREGISTER_COMMAND)
1492
write_stderr(_("%s: no database directory specified "
1493
"and environment variable PGDATA unset\n"),
1501
switch (ctl_command)
1503
case RESTART_COMMAND:
1515
if (ctl_command == RELOAD_COMMAND)
1521
snprintf(def_postopts_file, MAXPGPATH, "%s/postmaster.opts.default", pg_data);
1522
snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
1523
snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
1524
snprintf(conf_file, MAXPGPATH, "%s/postgresql.conf", pg_data);
1526
switch (ctl_command)
1528
case STATUS_COMMAND:
1537
case RESTART_COMMAND:
1540
case RELOAD_COMMAND:
1546
#if defined(WIN32) || defined(__CYGWIN__)
1547
case REGISTER_COMMAND:
1548
pgwin32_doRegister();
1550
case UNREGISTER_COMMAND:
1551
pgwin32_doUnregister();
1553
case RUN_AS_SERVICE_COMMAND:
1554
pgwin32_doRunAsService();