summaryrefslogtreecommitdiff
path: root/src/backend/postmaster/postmaster.c
blob: 4def9996f14e3458642995e41c13844391ae2b57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
/*-------------------------------------------------------------------------
 *
 * postmaster.c
 *	  This program acts as a clearing house for requests to the
 *	  POSTGRES system.	Frontend programs send a startup message
 *	  to the Postmaster and the postmaster uses the info in the
 *	  message to setup a backend process.
 *
 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *	  $Header: /cvsroot/pgsql/src/backend/postmaster/postmaster.c,v 1.197 2000/11/30 23:20:51 tgl Exp $
 *
 * NOTES
 *
 * Initialization:
 *		The Postmaster sets up a few shared memory data structures
 *		for the backends.  It should at the very least initialize the
 *		lock manager.
 *
 * Synchronization:
 *		The Postmaster shares memory with the backends and will have to lock
 *		the shared memory it accesses.	The Postmaster should never block
 *		on messages from clients.
 *
 * Garbage Collection:
 *		The Postmaster cleans up after backends if they have an emergency
 *		exit and/or core dump.
 *
 * Communication:
 *
 *-------------------------------------------------------------------------
 */

#include "postgres.h"

#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#include <sys/param.h>
/* moved here to prevent double define */
#include <netdb.h>
#include <limits.h>

#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif

#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif

#include "catalog/pg_database.h"
#include "commands/async.h"
#include "lib/dllist.h"
#include "libpq/auth.h"
#include "libpq/crypt.h"
#include "libpq/libpq.h"
#include "libpq/pqcomm.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "nodes/nodes.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/proc.h"
#include "access/xlog.h"
#include "tcop/tcopprot.h"
#include "utils/exc.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "bootstrap/bootstrap.h"

#define INVALID_SOCK	(-1)
#define ARGV_SIZE	64

#ifdef HAVE_SIGPROCMASK
sigset_t	UnBlockSig,
			BlockSig;

#else
int			UnBlockSig,
			BlockSig;

#endif

/*
 * Info for garbage collection.  Whenever a process dies, the Postmaster
 * cleans up after it.	Currently, NO information is required for cleanup,
 * but I left this structure around in case that changed.
 */
typedef struct bkend
{
	int			pid;			/* process id of backend */
	long		cancel_key;		/* cancel key for cancels for this backend */
} Backend;

/* list of active backends.  For garbage collection only now. */
static Dllist *BackendList;

/* list of ports associated with still open, but incomplete connections */
static Dllist *PortList;

/* The socket number we are listening for connections on */
int PostPortNumber;
char *UnixSocketDir;
char *VirtualHost;

/*
 * MaxBackends is the actual limit on the number of backends we will
 * start. The default is established by configure, but it can be
 * readjusted from 1..MAXBACKENDS with the postmaster -N switch. Note
 * that a larger MaxBackends value will increase the size of the shared
 * memory area as well as cause the postmaster to grab more kernel
 * semaphores, even if you never actually use that many backends.
 */
int	MaxBackends = DEF_MAXBACKENDS;


static char *progname = (char *) NULL;
static char **real_argv;
static int	real_argc;

static time_t tnow;

/* flag to indicate that SIGHUP arrived during server loop */
static volatile bool got_SIGHUP = false;

/*
 * Default Values
 */
static int	ServerSock_INET = INVALID_SOCK;		/* stream socket server */

#ifdef HAVE_UNIX_SOCKETS
static int	ServerSock_UNIX = INVALID_SOCK;		/* stream socket server */
#endif

#ifdef USE_SSL
static SSL_CTX *SSL_context = NULL;		/* Global SSL context */
#endif

/*
 * Set by the -o option
 */
static char ExtraOptions[MAXPGPATH];

/*
 * These globals control the behavior of the postmaster in case some
 * backend dumps core.	Normally, it kills all peers of the dead backend
 * and reinitializes shared memory.  By specifying -s or -n, we can have
 * the postmaster stop (rather than kill) peers and not reinitialize
 * shared data structures.
 */
static bool Reinit = true;
static int	SendStop = false;

bool NetServer = false;	/* listen on TCP/IP */
bool EnableSSL = false;
bool SilentMode = false;	/* silent mode (-S) */

int				CheckPointTimeout = 300;

static pid_t	StartupPID = 0,
				ShutdownPID = 0,
				CheckPointPID = 0;
static time_t	checkpointed = 0;

#define			NoShutdown		0
#define			SmartShutdown	1
#define			FastShutdown	2

static int	Shutdown = NoShutdown;

static bool FatalError = false;

/*
 * State for assigning random salts and cancel keys.
 * Also, the global MyCancelKey passes the cancel key assigned to a given
 * backend from the postmaster to that backend (via fork).
 */

static unsigned int random_seed = 0;

extern char *optarg;
extern int	optind,
			opterr;

/*
 * postmaster.c - function prototypes
 */
static void pmdaemonize(int argc, char *argv[]);
static Port *ConnCreate(int serverFd);
static void ConnFree(Port *port);
static void reset_shared(unsigned short port);
static void SIGHUP_handler(SIGNAL_ARGS);
static void pmdie(SIGNAL_ARGS);
static void reaper(SIGNAL_ARGS);
static void dumpstatus(SIGNAL_ARGS);
static void CleanupProc(int pid, int exitstatus);
static int	DoBackend(Port *port);
static void ExitPostmaster(int status);
static void usage(const char *);
static int	ServerLoop(void);
static int	BackendStartup(Port *port);
static int	readStartupPacket(void *arg, PacketLen len, void *pkt);
static int	processCancelRequest(Port *port, PacketLen len, void *pkt);
static int	initMasks(fd_set *rmask, fd_set *wmask);
static char *canAcceptConnections(void);
static long PostmasterRandom(void);
static void RandomSalt(char *salt);
static void SignalChildren(SIGNAL_ARGS);
static int	CountChildren(void);
static bool CreateOptsFile(int argc, char *argv[]);

static pid_t SSDataBase(int xlop);

#define StartupDataBase()		SSDataBase(BS_XLOG_STARTUP)
#define CheckPointDataBase()	SSDataBase(BS_XLOG_CHECKPOINT)
#define ShutdownDataBase()		SSDataBase(BS_XLOG_SHUTDOWN)

#ifdef USE_SSL
static void InitSSL(void);

#endif

#ifdef CYR_RECODE
extern void GetCharSetByHost(char *, int, char *);

#endif


static void
checkDataDir(const char *checkdir)
{
	char		path[MAXPGPATH];
	FILE	   *fp;

	if (checkdir == NULL)
	{
		fprintf(stderr, "%s does not know where to find the database system "
				"data.  You must specify the directory that contains the "
				"database system either by specifying the -D invocation "
				"option or by setting the PGDATA environment variable.\n\n",
				progname);
		ExitPostmaster(2);
	}

	snprintf(path, sizeof(path), "%s%cglobal%cpg_control",
			 checkdir, SEP_CHAR, SEP_CHAR);

	fp = AllocateFile(path, PG_BINARY_R);
	if (fp == NULL)
	{
		fprintf(stderr, "%s does not find the database system."
				"\n\tExpected to find it in the PGDATA directory \"%s\","
				"\n\tbut unable to open file \"%s\": %s\n\n",
				progname, checkdir, path, strerror(errno));
		ExitPostmaster(2);
	}

	FreeFile(fp);

	ValidatePgVersion(checkdir);
}


int
PostmasterMain(int argc, char *argv[])
{
	int			opt;
	int			status;
	char		original_extraoptions[MAXPGPATH];
	char       *potential_DataDir = NULL;

	IsUnderPostmaster = true;	/* so that backends know this */

	*original_extraoptions = '\0';

	progname = argv[0];
	real_argv = argv;
	real_argc = argc;

	/*
	 * Catch standard options before doing much else.  This even works
	 * on systems without getopt_long.
	 */
	if (argc > 1)
	{
		if (strcmp(argv[1], "--help")==0 || strcmp(argv[1], "-?")==0)
		{
			usage(progname);
			ExitPostmaster(0);
		}
		if (strcmp(argv[1], "--version")==0 || strcmp(argv[1], "-V")==0)
		{
			puts("postmaster (PostgreSQL) " PG_VERSION);
			ExitPostmaster(0);
		}
	}		


	/*
	 * for security, no dir or file created can be group or other
	 * accessible
	 */
	umask((mode_t) 0077);

	MyProcPid = getpid();

	/*
	 * Fire up essential subsystems: error and memory management
	 */
	EnableExceptionHandling(true);
	MemoryContextInit();

	/*
	 * By default, palloc() requests in the postmaster will be allocated
	 * in the PostmasterContext, which is space that can be recycled by
	 * backends.  Allocated data that needs to be available to backends
	 * should be allocated in TopMemoryContext.
	 */
	PostmasterContext = AllocSetContextCreate(TopMemoryContext,
											  "Postmaster",
											  ALLOCSET_DEFAULT_MINSIZE,
											  ALLOCSET_DEFAULT_INITSIZE,
											  ALLOCSET_DEFAULT_MAXSIZE);
	MemoryContextSwitchTo(PostmasterContext);

	/*
	 * Options setup
	 */
	potential_DataDir = getenv("PGDATA"); /* default value */

	ResetAllOptions();

	/*
	 * First we must scan for a -D argument to get the data dir. Then
	 * read the config file. Finally, scan all the other arguments.
	 * (Command line switches override config file.)
	 *
	 * Note: The two lists of options must be exactly the same, even
	 * though perhaps the first one would only have to be "D:" with
	 * opterr turned off. But some versions of getopt (notably GNU)
	 * are going to arbitrarily permute some "non-options" (according
	 * to the local world view) which will result in some switches
	 * being associated with the wrong argument. Death and destruction
	 * will occur.
	 */
	opterr = 1;
	while ((opt = getopt(argc, argv, "A:a:B:b:c:D:d:Fh:ik:lm:MN:no:p:Ss-:")) != EOF)
	{
		switch(opt)
		{
			case 'D':
				potential_DataDir = optarg;
				break;

			case '?':
				fprintf(stderr, "Try '%s --help' for more information.\n", progname);
				ExitPostmaster(1);
		}
	}

	/*
	 * Non-option switch arguments don't exist.
	 */
	if (optind < argc)
	{
		fprintf(stderr, "%s: invalid argument -- %s\n", progname, argv[optind]);
		fprintf(stderr, "Try '%s --help' for more information.\n", progname);
		ExitPostmaster(1);
	}

	checkDataDir(potential_DataDir);	/* issues error messages */
	SetDataDir(potential_DataDir);

	ProcessConfigFile(PGC_POSTMASTER);

	IgnoreSystemIndexes(false);

	optind = 1; /* start over */
#ifdef HAVE_INT_OPTRESET
	optreset = 1;
#endif
	while ((opt = getopt(argc, argv, "A:a:B:b:c:D:d:Fh:ik:lm:MN:no:p:Ss-:")) != EOF)
	{
		switch (opt)
		{
			case 'A':
#ifndef USE_ASSERT_CHECKING
				fprintf(stderr, "Assert checking is not compiled in\n");
#else
				assert_enabled = atoi(optarg);
#endif
				break;
			case 'a':
				/* Can no longer set authentication method. */
				break;
			case 'B':
				NBuffers = atoi(optarg);
				break;
			case 'b':
				/* Can no longer set the backend executable file to use. */
				break;
			case 'D':
				/* already done above */
				break;
			case 'd':

				/*
				 * Turn on debugging for the postmaster and the backend
				 * servers descended from it.
				 */
				DebugLvl = atoi(optarg);
				break;
			case 'F':
				enableFsync = false;
				break;
			case 'h':
				VirtualHost = optarg;
				break;
			case 'i':
				NetServer = true;
				break;
			case 'k':
				UnixSocketDir = optarg;
				break;
#ifdef USE_SSL
			case 'l':
			        EnableSSL = true;
				break;
#endif
			case 'm':
				/* Multiplexed backends no longer supported. */
				break;
			case 'M':

				/*
				 * ignore this flag.  This may be passed in because the
				 * program was run as 'postgres -M' instead of
				 * 'postmaster'
				 */
				break;
			case 'N':

				/*
				 * The max number of backends to start. Can't set to less
				 * than 1 or more than compiled-in limit.
				 */
				MaxBackends = atoi(optarg);
				if (MaxBackends < 1)
					MaxBackends = 1;
				if (MaxBackends > MAXBACKENDS)
					MaxBackends = MAXBACKENDS;
				break;
			case 'n':
				/* Don't reinit shared mem after abnormal exit */
				Reinit = false;
				break;
			case 'o':

				/*
				 * Other options to pass to the backend on the command
				 * line -- useful only for debugging.
				 */
				strcat(ExtraOptions, " ");
				strcat(ExtraOptions, optarg);
				strcpy(original_extraoptions, optarg);
				break;
			case 'p':
				PostPortNumber = atoi(optarg);
				break;
			case 'S':

				/*
				 * Start in 'S'ilent mode (disassociate from controlling
				 * tty). You may also think of this as 'S'ysV mode since
				 * it's most badly needed on SysV-derived systems like
				 * SVR4 and HP-UX.
				 */
				SilentMode = true;
				break;
			case 's':

				/*
				 * In the event that some backend dumps core, send
				 * SIGSTOP, rather than SIGUSR1, to all its peers.	This
				 * lets the wily post_hacker collect core dumps from
				 * everyone.
				 */
				SendStop = true;
				break;
			case 'c':
			case '-':
			{
				char *name, *value;

				ParseLongOption(optarg, &name, &value);
				if (!value)
				{
					if (opt == '-')
						elog(ERROR, "--%s requires argument", optarg);
					else
						elog(ERROR, "-c %s requires argument", optarg);
				}

				SetConfigOption(name, value, PGC_POSTMASTER);
				free(name);
				if (value)
					free(value);
				break;
			}

			default:
				/* shouldn't get here */
				fprintf(stderr, "Try '%s --help' for more information.\n", progname);
				ExitPostmaster(1);
		}
	}

	/*
	 * Check for invalid combinations of switches
	 */
	if (NBuffers < 2 * MaxBackends || NBuffers < 16)
	{

		/*
		 * Do not accept -B so small that backends are likely to starve
		 * for lack of buffers.  The specific choices here are somewhat
		 * arbitrary.
		 */
		fprintf(stderr, "%s: The number of buffers (-B) must be at least twice the number of allowed connections (-N) and at least 16.\n",
				progname);
		ExitPostmaster(1);
	}

	if (DebugLvl > 2)
	{
		extern char **environ;
		char	  **p;

		fprintf(stderr, "%s: PostmasterMain: initial environ dump:\n",
				progname);
		fprintf(stderr, "-----------------------------------------\n");
		for (p = environ; *p; ++p)
			fprintf(stderr, "\t%s\n", *p);
		fprintf(stderr, "-----------------------------------------\n");
	}

	/*
	 * Fork away from controlling terminal, if -S specified.
	 *
	 * Must do this before we grab any interlock files, else the interlocks
	 * will show the wrong PID.
	 */
	if (SilentMode)
		pmdaemonize(argc, argv);

	/*
	 * Create lockfile for data directory.
	 *
	 * We want to do this before we try to grab the input sockets, because
	 * the data directory interlock is more reliable than the socket-file
	 * interlock (thanks to whoever decided to put socket files in /tmp :-().
	 * For the same reason, it's best to grab the TCP socket before the
	 * Unix socket.
	 */
	if (! CreateDataDirLockFile(DataDir, true))
		ExitPostmaster(1);

	/*
	 * Establish input sockets.
	 */
#ifdef USE_SSL
	if (EnableSSL && !NetServer)
	{
		fprintf(stderr, "%s: For SSL, TCP/IP connections must be enabled. See -? for help.\n",
				progname);
		ExitPostmaster(1);
	}
	if (EnableSSL)
	        InitSSL();
#endif

	if (NetServer)
	{
		status = StreamServerPort(AF_INET, VirtualHost,
						(unsigned short) PostPortNumber, UnixSocketDir,
						&ServerSock_INET);
		if (status != STATUS_OK)
		{
			fprintf(stderr, "%s: cannot create INET stream port\n",
					progname);
			ExitPostmaster(1);
		}
	}

#ifdef HAVE_UNIX_SOCKETS
	status = StreamServerPort(AF_UNIX, VirtualHost,
						(unsigned short) PostPortNumber, UnixSocketDir, 
						&ServerSock_UNIX);
	if (status != STATUS_OK)
	{
		fprintf(stderr, "%s: cannot create UNIX stream port\n",
				progname);
		ExitPostmaster(1);
	}
#endif

	XLOGPathInit();

	/*
	 * Set up shared memory and semaphores.
	 */
	reset_shared(PostPortNumber);

	/*
	 * Initialize the list of active backends.	This list is only used for
	 * garbage collecting the backend processes.
	 */
	BackendList = DLNewList();
	PortList = DLNewList();

	/*
	 * Record postmaster options.  We delay this till now to avoid recording
	 * bogus options (eg, NBuffers too high for available memory).
	 */
	if (!CreateOptsFile(argc, argv))
		ExitPostmaster(1);

	/*
	 * Set up signal handlers for the postmaster process.
	 */
	pqinitmask();
	PG_SETMASK(&BlockSig);

	pqsignal(SIGHUP, SIGHUP_handler);	/* reread config file and have children do same */
	pqsignal(SIGINT, pmdie);	/* send SIGTERM and ShutdownDataBase */
	pqsignal(SIGQUIT, pmdie);	/* send SIGUSR1 and die */
	pqsignal(SIGTERM, pmdie);	/* wait for children and ShutdownDataBase */
	pqsignal(SIGALRM, SIG_IGN); /* ignored */
	pqsignal(SIGPIPE, SIG_IGN); /* ignored */
	pqsignal(SIGUSR1, SIG_IGN); /* ignored */
	pqsignal(SIGUSR2, pmdie);	/* send SIGUSR2, don't die */
	pqsignal(SIGCHLD, reaper);	/* handle child termination */
	pqsignal(SIGTTIN, SIG_IGN); /* ignored */
	pqsignal(SIGTTOU, SIG_IGN); /* ignored */
	pqsignal(SIGWINCH, dumpstatus);		/* dump port status */

	/*
	 * We're ready to rock and roll...
	 */
	StartupPID = StartupDataBase();

	status = ServerLoop();

	/*
	 * ServerLoop probably shouldn't ever return, but if it does, close down.
	 */
	ExitPostmaster(status != STATUS_OK);

	return 0;					/* not reached */
}

static void
pmdaemonize(int argc, char *argv[])
{
	int			i;
	pid_t		pid;

	pid = fork();
	if (pid == (pid_t) -1)
	{
		perror("Failed to fork postmaster");
		ExitPostmaster(1);
		return;					/* not reached */
	}
	else if (pid)
	{							/* parent */
		/* Parent should just exit, without doing any atexit cleanup */
		_exit(0);
	}

	MyProcPid = getpid();		/* reset MyProcPid to child */

/* GH: If there's no setsid(), we hopefully don't need silent mode.
 * Until there's a better solution.
 */
#ifdef HAVE_SETSID
	if (setsid() < 0)
	{
		fprintf(stderr, "%s: ", progname);
		perror("cannot disassociate from controlling TTY");
		ExitPostmaster(1);
	}
#endif
	i = open(NULL_DEV, O_RDWR | PG_BINARY);
	dup2(i, 0);
	dup2(i, 1);
	dup2(i, 2);
	close(i);
}



/*
 * Print out help message
 */
static void
usage(const char *progname)
{
	printf("%s is the PostgreSQL server.\n\n", progname);
	printf("Usage:\n  %s [options...]\n\n", progname);
	printf("Options:\n");
#ifdef USE_ASSERT_CHECKING
	printf("  -A 1|0          enable/disable run-time assert checking\n");
#endif
	printf("  -B NBUFFERS     number of shared buffers (default %d)\n", DEF_NBUFFERS);
	printf("  -c NAME=VALUE   set run-time parameter\n");
	printf("  -d 1-5          debugging level\n");
	printf("  -D DATADIR      database directory\n");
	printf("  -F              turn fsync off\n");
	printf("  -h HOSTNAME     host name or IP address to listen on\n");
	printf("  -i              enable TCP/IP connections\n");
	printf("  -k DIRECTORY    Unix-domain socket location\n");
#ifdef USE_SSL
	printf("  -l              enable SSL connections\n");
#endif
	printf("  -N MAX-CONNECT  maximum number of allowed connections (1..%d, default %d)\n",
			MAXBACKENDS, DEF_MAXBACKENDS);
	printf("  -o OPTIONS      pass 'OPTIONS' to each backend server\n");
	printf("  -p PORT         port number to listen on (default %d)\n", DEF_PGPORT);
	printf("  -S              silent mode (start in background without logging output)\n");

	printf("\nDeveloper options:\n");
	printf("  -n              do not reinitialize shared memory after abnormal exit\n");
	printf("  -s              send SIGSTOP to all backend servers if one dies\n");

	printf("\nPlease read the documentation for the complete list of run-time\n"
		   "configuration settings and how to set them on the command line or in\n"
		   "the configuration file.\n\n");

	printf("Report bugs to <pgsql-bugs@postgresql.org>.\n");
}

static int
ServerLoop(void)
{
	fd_set		readmask,
				writemask;
	int			nSockets;
	Dlelem	   *curr;
	struct timeval now,
				later;
	struct timezone tz;

	gettimeofday(&now, &tz);

	nSockets = initMasks(&readmask, &writemask);

	for (;;)
	{
		Port		   *port;
		fd_set			rmask,
						wmask;
		struct timeval *timeout = NULL;
		struct timeval	timeout_tv;

		if (CheckPointPID == 0 && checkpointed && !FatalError)
		{
			time_t	now = time(NULL);

			if (CheckPointTimeout + checkpointed > now)
			{
				timeout_tv.tv_sec = CheckPointTimeout + checkpointed - now;
				timeout_tv.tv_usec = 0;
				timeout = &timeout_tv;
			}
			else
				CheckPointPID = CheckPointDataBase();
		}

#ifdef USE_SSL
		/*
		 * If we are using SSL, there may be input data already read and
		 * pending in SSL's input buffers.  If so, check for additional
		 * input from other clients, but don't delay before processing.
		 */
		for (curr = DLGetHead(PortList); curr; curr = DLGetSucc(curr))
		{
			Port	   *port = (Port *) DLE_VAL(curr);

			if (port->ssl && SSL_pending(port->ssl))
			{
				timeout_tv.tv_sec = 0;
				timeout_tv.tv_usec = 0;
				timeout = &timeout_tv;
				break;
			}
		}
#endif

		/*
		 * Wait for something to happen.
		 */
		memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
		memcpy((char *) &wmask, (char *) &writemask, sizeof(fd_set));

		PG_SETMASK(&UnBlockSig);

		if (select(nSockets, &rmask, &wmask, (fd_set *) NULL, timeout) < 0)
		{
			PG_SETMASK(&BlockSig);
			if (errno == EINTR || errno == EWOULDBLOCK)
				continue;
			fprintf(stderr, "%s: ServerLoop: select failed: %s\n",
					progname, strerror(errno));
			return STATUS_ERROR;
		}

		/*
		 * Block all signals until we wait again
		 */
		PG_SETMASK(&BlockSig);

		/*
		 * Respond to signals, if needed
		 */
		if (got_SIGHUP)
		{
			got_SIGHUP = false;
			ProcessConfigFile(PGC_SIGHUP);
		}

		/*
		 * Select a random seed at the time of first receiving a request.
		 */
		while (random_seed == 0)
		{
			gettimeofday(&later, &tz);

			/*
			 * We are not sure how much precision is in tv_usec, so we
			 * swap the nibbles of 'later' and XOR them with 'now'. On the
			 * off chance that the result is 0, we loop until it isn't.
			 */
			random_seed = now.tv_usec ^
				((later.tv_usec << 16) |
				 ((later.tv_usec >> 16) & 0xffff));
		}

		/*
		 * new connection pending on our well-known port's socket?
		 */

#ifdef HAVE_UNIX_SOCKETS
		if (ServerSock_UNIX != INVALID_SOCK &&
			FD_ISSET(ServerSock_UNIX, &rmask) &&
			(port = ConnCreate(ServerSock_UNIX)) != NULL)
		{
			PacketReceiveSetup(&port->pktInfo,
							   readStartupPacket,
							   (void *) port);
		}
#endif

		if (ServerSock_INET != INVALID_SOCK &&
			FD_ISSET(ServerSock_INET, &rmask) &&
			(port = ConnCreate(ServerSock_INET)) != NULL)
		{
			PacketReceiveSetup(&port->pktInfo,
							   readStartupPacket,
							   (void *) port);
		}

		/*
		 * Scan active ports, processing any available input.  While we
		 * are at it, build up new masks for next select().
		 */
		nSockets = initMasks(&readmask, &writemask);

		curr = DLGetHead(PortList);

		while (curr)
		{
			Port	   *port = (Port *) DLE_VAL(curr);
			int			status = STATUS_OK;
			Dlelem	   *next;

			if (FD_ISSET(port->sock, &rmask)
#ifdef USE_SSL
				|| (port->ssl && SSL_pending(port->ssl))
#endif
				)
			{
				if (DebugLvl > 1)
					fprintf(stderr, "%s: ServerLoop:\t\thandling reading %d\n",
							progname, port->sock);

				if (PacketReceiveFragment(port) != STATUS_OK)
					status = STATUS_ERROR;
			}

			if (FD_ISSET(port->sock, &wmask))
			{
				if (DebugLvl > 1)
					fprintf(stderr, "%s: ServerLoop:\t\thandling writing %d\n",
							progname, port->sock);

				if (PacketSendFragment(port) != STATUS_OK)
					status = STATUS_ERROR;
			}

			/* Get this before the connection might be closed. */

			next = DLGetSucc(curr);

			/*
			 * If there is no error and no outstanding data transfer going
			 * on, then the authentication handshake must be complete to
			 * the postmaster's satisfaction.  So, start the backend.
			 */

			if (status == STATUS_OK && port->pktInfo.state == Idle)
			{
				/*
				 * Can we accept a connection now?
				 *
				 * Even though readStartupPacket() already checked,
				 * we have to check again in case conditions changed
				 * while negotiating authentication.
				 */
				char   *rejectMsg = canAcceptConnections();

				if (rejectMsg != NULL)
				{
					PacketSendError(&port->pktInfo, rejectMsg);
				}
				else
				{

					/*
					 * If the backend start fails then keep the connection
					 * open to report it.  Otherwise, pretend there is an
					 * error to close our descriptor for the connection,
					 * which will now be managed by the backend.
					 */
					if (BackendStartup(port) != STATUS_OK)
						PacketSendError(&port->pktInfo,
										"Backend startup failed");
					else
						status = STATUS_ERROR;
				}
			}

			/* Close the connection if required. */

			if (status != STATUS_OK)
			{
				StreamClose(port->sock);
				DLRemove(curr);
				ConnFree(port);
				DLFreeElem(curr);
			}
			else
			{
				/* Set the masks for this connection. */

				if (nSockets <= port->sock)
					nSockets = port->sock + 1;

				if (port->pktInfo.state == WritingPacket)
					FD_SET(port->sock, &writemask);
				else
					FD_SET(port->sock, &readmask);
			}

			curr = next;
		} /* loop over active ports */
	}
}


/*
 * Initialise the read and write masks for select() for the well-known ports
 * we are listening on.  Return the number of sockets to listen on.
 */

static int
initMasks(fd_set *rmask, fd_set *wmask)
{
	int			nsocks = -1;

	FD_ZERO(rmask);
	FD_ZERO(wmask);

#ifdef HAVE_UNIX_SOCKETS
	if (ServerSock_UNIX != INVALID_SOCK)
	{
		FD_SET(ServerSock_UNIX, rmask);

		if (ServerSock_UNIX > nsocks)
			nsocks = ServerSock_UNIX;
	}
#endif

	if (ServerSock_INET != INVALID_SOCK)
	{
		FD_SET(ServerSock_INET, rmask);
		if (ServerSock_INET > nsocks)
			nsocks = ServerSock_INET;
	}

	return nsocks + 1;
}


/*
 * Called when the startup packet has been read.
 */

static int
readStartupPacket(void *arg, PacketLen len, void *pkt)
{
	Port	   *port;
	StartupPacket *si;
	char	   *rejectMsg;

	port = (Port *) arg;
	si = (StartupPacket *) pkt;

	/*
	 * The first field is either a protocol version number or a special
	 * request code.
	 */

	port->proto = ntohl(si->protoVersion);

	if (port->proto == CANCEL_REQUEST_CODE)
		return processCancelRequest(port, len, pkt);

	if (port->proto == NEGOTIATE_SSL_CODE)
	{
		char		SSLok;

#ifdef USE_SSL
		/* No SSL when disabled or on Unix sockets */
		if (!EnableSSL || port->laddr.sa.sa_family != AF_INET)
			SSLok = 'N';
		else
			SSLok = 'S';		/* Support for SSL */
#else
		SSLok = 'N';			/* No support for SSL */
#endif
		if (send(port->sock, &SSLok, 1, 0) != 1)
		{
			perror("Failed to send SSL negotiation response");
			return STATUS_ERROR; /* Close connection */
		}

#ifdef USE_SSL
		if (SSLok == 'S')
		{
		  if (!(port->ssl = SSL_new(SSL_context)) ||
		      !SSL_set_fd(port->ssl, port->sock) ||
		      SSL_accept(port->ssl) <= 0)
		    {
		      fprintf(stderr, "Failed to initialize SSL connection: %s, errno: %d (%s)\n",
			      ERR_reason_error_string(ERR_get_error()), errno, strerror(errno));
		      return STATUS_ERROR;
		    }
		}
#endif
		/* ready for the normal startup packet */
		PacketReceiveSetup(&port->pktInfo,
						   readStartupPacket,
						   (void *) port);
		return STATUS_OK;		/* Do not close connection */
	}

	/* Could add additional special packet types here */


	/* Check we can handle the protocol the frontend is using. */

	if (PG_PROTOCOL_MAJOR(port->proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
		PG_PROTOCOL_MAJOR(port->proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
		(PG_PROTOCOL_MAJOR(port->proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
		 PG_PROTOCOL_MINOR(port->proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
	{
		PacketSendError(&port->pktInfo, "Unsupported frontend protocol.");
		return STATUS_OK;		/* don't close the connection yet */
	}

	/*
	 * Get the parameters from the startup packet as C strings.  The
	 * packet destination was cleared first so a short packet has zeros
	 * silently added and a long packet is silently truncated.
	 */

	StrNCpy(port->database, si->database, sizeof(port->database));
	StrNCpy(port->user, si->user, sizeof(port->user));
	StrNCpy(port->options, si->options, sizeof(port->options));
	StrNCpy(port->tty, si->tty, sizeof(port->tty));

	/* The database defaults to the user name. */

	if (port->database[0] == '\0')
		StrNCpy(port->database, si->user, sizeof(port->database));

	/* Check a user name was given. */

	if (port->user[0] == '\0')
	{
		PacketSendError(&port->pktInfo,
					"No Postgres username specified in startup packet.");
		return STATUS_OK;		/* don't close the connection yet */
	}

	/*
	 * If we're going to reject the connection due to database state,
	 * say so now instead of wasting cycles on an authentication exchange.
	 * (This also allows a pg_ping utility to be written.)
	 */
	rejectMsg = canAcceptConnections();

	if (rejectMsg != NULL)
	{
		PacketSendError(&port->pktInfo, rejectMsg);
		return STATUS_OK;		/* don't close the connection yet */
	}

	/* Start the authentication itself. */

	be_recvauth(port);

	return STATUS_OK;			/* don't close the connection yet */
}

/*
 * The client has sent a cancel request packet, not a normal
 * start-a-new-backend packet.	Perform the necessary processing.
 * Note that in any case, we return STATUS_ERROR to close the
 * connection immediately.	Nothing is sent back to the client.
 */

static int
processCancelRequest(Port *port, PacketLen len, void *pkt)
{
	CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
	int			backendPID;
	long		cancelAuthCode;
	Dlelem	   *curr;
	Backend    *bp;

	backendPID = (int) ntohl(canc->backendPID);
	cancelAuthCode = (long) ntohl(canc->cancelAuthCode);

	if (backendPID == CheckPointPID)
	{
		if (DebugLvl)
			fprintf(stderr, "%s: processCancelRequest: CheckPointPID in cancel request for process %d\n",
					progname, backendPID);
		return STATUS_ERROR;
	}

	/* See if we have a matching backend */

	for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
	{
		bp = (Backend *) DLE_VAL(curr);
		if (bp->pid == backendPID)
		{
			if (bp->cancel_key == cancelAuthCode)
			{
				/* Found a match; signal that backend to cancel current op */
				if (DebugLvl)
					fprintf(stderr, "%s: processCancelRequest: sending SIGINT to process %d\n",
							progname, bp->pid);
				kill(bp->pid, SIGINT);
			}
			else
			{
				/* Right PID, wrong key: no way, Jose */
				if (DebugLvl)
					fprintf(stderr, "%s: processCancelRequest: bad key in cancel request for process %d\n",
							progname, bp->pid);
			}
			return STATUS_ERROR;
		}
	}

	/* No matching backend */
	if (DebugLvl)
		fprintf(stderr, "%s: processCancelRequest: bad PID in cancel request for process %d\n",
				progname, backendPID);

	return STATUS_ERROR;
}

/*
 * canAcceptConnections --- check to see if database state allows connections.
 *
 * If we are open for business, return NULL, otherwise return an error message
 * string suitable for rejecting a connection request.
 */
static char *
canAcceptConnections(void)
{
	/* Can't start backends when in startup/shutdown/recovery state. */
	if (Shutdown > NoShutdown)
		return "The Data Base System is shutting down";
	if (StartupPID)
		return "The Data Base System is starting up";
	if (FatalError)
		return "The Data Base System is in recovery mode";
	/* Can't start backend if max backend count is exceeded. */
	if (CountChildren() >= MaxBackends)
		return "Sorry, too many clients already";

	return NULL;
}

/*
 * ConnCreate -- create a local connection data structure
 */
static Port *
ConnCreate(int serverFd)
{
	Port	   *port;

	if (!(port = (Port *) calloc(1, sizeof(Port))))
	{
		fprintf(stderr, "%s: ConnCreate: malloc failed\n",
				progname);
		SignalChildren(SIGUSR1);
		ExitPostmaster(1);
	}

	if (StreamConnection(serverFd, port) != STATUS_OK)
	{
		StreamClose(port->sock);
		ConnFree(port);
		port = NULL;
	}
	else
	{
		DLAddHead(PortList, DLNewElem(port));
		RandomSalt(port->salt);
		port->pktInfo.state = Idle;
	}

	return port;
}

/*
 * ConnFree -- free a local connection data structure
 */
static void
ConnFree(Port *conn)
{
#ifdef USE_SSL
	if (conn->ssl)
		SSL_free(conn->ssl);
#endif
	free(conn);
}


/*
 * reset_shared -- reset shared memory and semaphores
 */
static void
reset_shared(unsigned short port)
{
	/*
	 * Reset assignment of shared mem and semaphore IPC keys.
	 * Doing this means that in normal cases we'll assign the same keys
	 * on each "cycle of life", and thereby avoid leaving dead IPC objects
	 * floating around if the postmaster crashes and is restarted.
	 */
	IpcInitKeyAssignment(port);
	/*
	 * Create or re-create shared memory and semaphores.
	 */
	CreateSharedMemoryAndSemaphores(false, MaxBackends);
}


/*
 * Set flag if SIGHUP was detected so config file can be reread in
 * main loop
 */
static void
SIGHUP_handler(SIGNAL_ARGS)
{
	if (Shutdown > SmartShutdown)
		return;
	got_SIGHUP = true;
	SignalChildren(SIGHUP);
}



/*
 * pmdie -- signal handler for cleaning up after a kill signal.
 */
static void
pmdie(SIGNAL_ARGS)
{
	PG_SETMASK(&BlockSig);

	if (DebugLvl >= 1)
		elog(DEBUG, "pmdie %d", postgres_signal_arg);

	switch (postgres_signal_arg)
	{
		case SIGUSR2:

			/*
			 * Send SIGUSR2 to all children (AsyncNotifyHandler)
			 */
			if (Shutdown > SmartShutdown)
				return;
			SignalChildren(SIGUSR2);
			return;

		case SIGTERM:

			/*
			 * Smart Shutdown:
			 *
			 * let children to end their work and ShutdownDataBase.
			 */
			if (Shutdown >= SmartShutdown)
				return;
			Shutdown = SmartShutdown;
			tnow = time(NULL);
			fprintf(stderr, "Smart Shutdown request at %s", ctime(&tnow));
			fflush(stderr);
			if (DLGetHead(BackendList)) /* let reaper() handle this */
				return;

			/*
			 * No children left. Shutdown data base system.
			 */
			if (StartupPID > 0 || FatalError)	/* let reaper() handle
												 * this */
				return;
			if (ShutdownPID > 0)
				abort();

			ShutdownPID = ShutdownDataBase();
			return;

		case SIGINT:

			/*
			 * Fast Shutdown:
			 *
			 * abort all children with SIGTERM (rollback active transactions
			 * and exit) and ShutdownDataBase.
			 */
			if (Shutdown >= FastShutdown)
				return;
			tnow = time(NULL);
			fprintf(stderr, "Fast Shutdown request at %s", ctime(&tnow));
			fflush(stderr);
			if (DLGetHead(BackendList)) /* let reaper() handle this */
			{
				Shutdown = FastShutdown;
				if (!FatalError)
				{
					fprintf(stderr, "Aborting any active transaction...\n");
					fflush(stderr);
					SignalChildren(SIGTERM);
				}
				return;
			}
			if (Shutdown > NoShutdown)
			{
				Shutdown = FastShutdown;
				return;
			}
			Shutdown = FastShutdown;

			/*
			 * No children left. Shutdown data base system.
			 */
			if (StartupPID > 0 || FatalError)	/* let reaper() handle
												 * this */
				return;
			if (ShutdownPID > 0)
				abort();

			ShutdownPID = ShutdownDataBase();
			return;

		case SIGQUIT:

			/*
			 * Immediate Shutdown:
			 *
			 * abort all children with SIGUSR1 and exit without attempt to
			 * properly shutdown data base system.
			 */
			tnow = time(NULL);
			fprintf(stderr, "Immediate Shutdown request at %s", ctime(&tnow));
			fflush(stderr);
			if (ShutdownPID > 0)
				kill(ShutdownPID, SIGQUIT);
			else if (StartupPID > 0)
				kill(StartupPID, SIGQUIT);
			else if (DLGetHead(BackendList))
				SignalChildren(SIGUSR1);
			break;
	}

	/* exit postmaster */
	ExitPostmaster(0);
}

/*
 * Reaper -- signal handler to cleanup after a backend (child) dies.
 */
static void
reaper(SIGNAL_ARGS)
{
/* GH: replace waitpid for !HAVE_WAITPID. Does this work ? */
#ifdef HAVE_WAITPID
	int			status;			/* backend exit status */

#else
	union wait	status;			/* backend exit status */

#endif
	int			exitstatus;
	int			pid;			/* process id of dead backend */

	PG_SETMASK(&BlockSig);

	if (DebugLvl)
		fprintf(stderr, "%s: reaping dead processes...\n",
				progname);
#ifdef HAVE_WAITPID
	while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
	{
		exitstatus = status;
#else
	while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
	{
		exitstatus = status.w_status;
#endif
		if (ShutdownPID > 0)
		{
			if (pid != ShutdownPID)
				abort();
			if (exitstatus != 0)
			{
				fprintf(stderr, "Shutdown failed - abort\n");
				fflush(stderr);
				ExitPostmaster(1);
			}
			ExitPostmaster(0);
		}
		if (StartupPID > 0)
		{
			if (pid != StartupPID)
				abort();
			if (exitstatus != 0)
			{
				fprintf(stderr, "Startup failed - abort\n");
				fflush(stderr);
				ExitPostmaster(1);
			}
			StartupPID = 0;
			FatalError = false;
			if (Shutdown > NoShutdown)
			{
				if (ShutdownPID > 0)
					abort();
				ShutdownPID = ShutdownDataBase();
			}

			/*
			 * Startup succeeded - remember its ID
			 */
			SetThisStartUpID();

			CheckPointPID = 0;
			checkpointed = time(NULL);

			pqsignal(SIGCHLD, reaper);
			return;
		}
		CleanupProc(pid, exitstatus);
	}
	pqsignal(SIGCHLD, reaper);

	if (FatalError)
	{

		/*
		 * Wait for all children exit, then reset shmem and StartupDataBase.
		 */
		if (DLGetHead(BackendList))
			return;
		if (StartupPID > 0 || ShutdownPID > 0)
			return;
		tnow = time(NULL);
		fprintf(stderr, "Server processes were terminated at %s"
				"Reinitializing shared memory and semaphores\n",
				ctime(&tnow));
		fflush(stderr);

		shmem_exit(0);
		reset_shared(PostPortNumber);

		StartupPID = StartupDataBase();
		return;
	}

	if (Shutdown > NoShutdown)
	{
		if (DLGetHead(BackendList))
			return;
		if (StartupPID > 0 || ShutdownPID > 0)
			return;
		ShutdownPID = ShutdownDataBase();
	}

}

/*
 * CleanupProc -- cleanup after terminated backend.
 *
 * Remove all local state associated with backend.
 *
 * Dillon's note: should log child's exit status in the system log.
 */
static void
CleanupProc(int pid,
			int exitstatus)		/* child's exit status. */
{
	Dlelem	   *curr,
			   *next;
	Backend    *bp;
	int			sig;

	if (DebugLvl)
	{
		fprintf(stderr, "%s: CleanupProc: pid %d exited with status %d\n",
				progname, pid, exitstatus);
	}

	/*
	 * If a backend dies in an ugly way (i.e. exit status not 0) then we
	 * must signal all other backends to quickdie.	If exit status is zero
	 * we assume everything is hunky dory and simply remove the backend
	 * from the active backend list.
	 */
	if (!exitstatus)
	{
		curr = DLGetHead(BackendList);
		while (curr)
		{
			bp = (Backend *) DLE_VAL(curr);
			if (bp->pid == pid)
			{
				DLRemove(curr);
				free(bp);
				DLFreeElem(curr);
				break;
			}
			curr = DLGetSucc(curr);
		}

		if (pid == CheckPointPID)
		{
			CheckPointPID = 0;
			checkpointed = time(NULL);
		}
		else
			ProcRemove(pid);

		return;
	}

	if (!FatalError)
	{
		tnow = time(NULL);
		fprintf(stderr, "Server process (pid %d) exited with status %d at %s"
				"Terminating any active server processes...\n",
				pid, exitstatus, ctime(&tnow));
		fflush(stderr);
	}
	FatalError = true;
	curr = DLGetHead(BackendList);
	while (curr)
	{
		next = DLGetSucc(curr);
		bp = (Backend *) DLE_VAL(curr);

		/*
		 * SIGUSR1 is the special signal that says exit without proc_exit
		 * and let the user know what's going on. ProcSemaphoreKill()
		 * cleans up the backends semaphore.  If SendStop is set (-s on
		 * command line), then we send a SIGSTOP so that we can core dumps
		 * from all backends by hand.
		 */
		sig = (SendStop) ? SIGSTOP : SIGUSR1;
		if (bp->pid != pid)
		{
			if (DebugLvl)
				fprintf(stderr, "%s: CleanupProc: sending %s to process %d\n",
						progname,
						(sig == SIGUSR1)
						? "SIGUSR1" : "SIGSTOP",
						bp->pid);
			kill(bp->pid, sig);
		}
		else
		{

			/*
			 * I don't like that we call ProcRemove() here, assuming that
			 * shmem may be corrupted! But is there another way to free
			 * backend semaphores? Actually, I believe that we need not in
			 * per backend semaphore at all (we use them to wait on lock
			 * only, couldn't we just sigpause?), so probably we'll remove
			 * this call from here someday.  -- vadim 04-10-1999
			 */
			if (pid == CheckPointPID)
			{
				CheckPointPID = 0;
				checkpointed = 0;
			}
			else
				ProcRemove(pid);

			DLRemove(curr);
			free(bp);
			DLFreeElem(curr);
		}
		curr = next;
	}

}

/*
 * Send a signal to all chidren processes.
 */
static void
SignalChildren(int signal)
{
	Dlelem	   *curr,
			   *next;
	Backend    *bp;
	int			mypid = getpid();

	curr = DLGetHead(BackendList);
	while (curr)
	{
		next = DLGetSucc(curr);
		bp = (Backend *) DLE_VAL(curr);

		if (bp->pid != mypid)
		{
			if (DebugLvl >= 1)
				elog(DEBUG, "SignalChildren: sending signal %d to process %d",
					 signal, bp->pid);

			kill(bp->pid, signal);
		}

		curr = next;
	}
}

/*
 * BackendStartup -- start backend process
 *
 * returns: STATUS_ERROR if the fork/exec failed, STATUS_OK
 *		otherwise.
 *
 */
static int
BackendStartup(Port *port)
{
	Backend    *bn;				/* for backend cleanup */
	int			pid;

	/*
	 * Compute the cancel key that will be assigned to this backend. The
	 * backend will have its own copy in the forked-off process' value of
	 * MyCancelKey, so that it can transmit the key to the frontend.
	 */
	MyCancelKey = PostmasterRandom();

	/*
	 * Flush stdio channels just before fork, to avoid double-output
	 * problems. Ideally we'd use fflush(NULL) here, but there are still a
	 * few non-ANSI stdio libraries out there (like SunOS 4.1.x) that
	 * coredump if we do. Presently stdout and stderr are the only stdio
	 * output channels used by the postmaster, so fflush'ing them should
	 * be sufficient.
	 */
	fflush(stdout);
	fflush(stderr);

#ifdef __BEOS__
	/* Specific beos actions before backend startup */
	beos_before_backend_startup();
#endif

	if ((pid = fork()) == 0)
	{							/* child */
#ifdef __BEOS__
		/* Specific beos backend startup actions */
		beos_backend_startup();
#endif

#ifdef CYR_RECODE
		{
			/* Save charset for this host while we still have client addr */
			char		ChTable[80];
			static char cyrEnvironment[100];

			GetCharSetByHost(ChTable, port->raddr.in.sin_addr.s_addr, DataDir);
			if (*ChTable != '\0')
			{
				snprintf(cyrEnvironment, sizeof(cyrEnvironment),
						 "PG_RECODETABLE=%s", ChTable);
				putenv(cyrEnvironment);
			}
		}
#endif

		if (DoBackend(port))
		{
			fprintf(stderr, "%s child[%d]: BackendStartup: backend startup failed\n",
					progname, (int) getpid());
			ExitPostmaster(1);
		}
		else
			ExitPostmaster(0);
	}

	/* in parent */
	if (pid < 0)
	{
#ifdef __BEOS__
		/* Specific beos backend startup actions */
		beos_backend_startup_failed();
#endif
		fprintf(stderr, "%s: BackendStartup: fork failed: %s\n",
				progname, strerror(errno));
		return STATUS_ERROR;
	}

	if (DebugLvl)
		fprintf(stderr, "%s: BackendStartup: pid %d user %s db %s socket %d\n",
				progname, pid, port->user, port->database,
				port->sock);

	/*
	 * Everything's been successful, it's safe to add this backend to our
	 * list of backends.
	 */
	if (!(bn = (Backend *) calloc(1, sizeof(Backend))))
	{
		fprintf(stderr, "%s: BackendStartup: malloc failed\n",
				progname);
		ExitPostmaster(1);
	}

	bn->pid = pid;
	bn->cancel_key = MyCancelKey;
	DLAddHead(BackendList, DLNewElem(bn));

	return STATUS_OK;
}

/*
 * split_opts -- split a string of options and append it to an argv array
 *
 * NB: the string is destructively modified!
 *
 * Since no current POSTGRES arguments require any quoting characters,
 * we can use the simple-minded tactic of assuming each set of space-
 * delimited characters is a separate argv element.
 *
 * If you don't like that, well, we *used* to pass the whole option string
 * as ONE argument to execl(), which was even less intelligent...
 */
static void
split_opts(char **argv, int *argcp, char *s)
{
	while (s && *s)
	{
		while (isspace((int) *s))
			++s;
		if (*s == '\0')
			break;
		argv[(*argcp)++] = s;
		while (*s && !isspace((int) *s))
			++s;
		if (*s)
			*s++ = '\0';
	}
}

/*
 * DoBackend -- set up the backend's argument list and invoke backend main().
 *
 * This used to perform an execv() but we no longer exec the backend;
 * it's the same executable as the postmaster.
 *
 * returns:
 *		Shouldn't return at all.
 *		If PostgresMain() fails, return status.
 */
static int
DoBackend(Port *port)
{
	char	   *av[ARGV_SIZE * 2];
	int			ac = 0;
	char		debugbuf[ARGV_SIZE];
	char		protobuf[ARGV_SIZE];
	char		dbbuf[ARGV_SIZE];
	char		optbuf[ARGV_SIZE];
	char		ttybuf[ARGV_SIZE];
	int			i;
	struct timeval now;
	struct timezone tz;

	/*
	 * Let's clean up ourselves as the postmaster child
	 */

	/* We don't want the postmaster's proc_exit() handlers */
	on_exit_reset();

	/*
	 * Signal handlers setting is moved to tcop/postgres...
	 */

	/* Close the postmaster sockets */
	if (NetServer)
		StreamClose(ServerSock_INET);
	ServerSock_INET = INVALID_SOCK;
#ifdef HAVE_UNIX_SOCKETS
	StreamClose(ServerSock_UNIX);
	ServerSock_UNIX = INVALID_SOCK;
#endif

	/* Save port etc. for ps status */
	MyProcPort = port;

	/* Reset MyProcPid to new backend's pid */
	MyProcPid = getpid();

	/*
	 * Don't want backend to be able to see the postmaster random number
	 * generator state.  We have to clobber the static random_seed *and*
	 * start a new random sequence in the random() library function.
	 */
	random_seed = 0;
	gettimeofday(&now, &tz);
	srandom((unsigned int) now.tv_usec);

	/* ----------------
	 * Now, build the argv vector that will be given to PostgresMain.
	 *
	 * The layout of the command line is
	 *		postgres [secure switches] -p databasename [insecure switches]
	 * where the switches after -p come from the client request.
	 * ----------------
	 */

	av[ac++] = "postgres";

	/*
	 * Pass the requested debugging level along to the backend. Level one
	 * debugging in the postmaster traces postmaster connection activity,
	 * and levels two and higher are passed along to the backend.  This
	 * allows us to watch only the postmaster or the postmaster and the
	 * backend.
	 */
	if (DebugLvl > 1)
	{
		sprintf(debugbuf, "-d%d", DebugLvl);
		av[ac++] = debugbuf;
	}

	/*
	 * Pass any backend switches specified with -o in the postmaster's own
	 * command line.  We assume these are secure. (It's OK to mangle
	 * ExtraOptions since we are now in the child process; this won't
	 * change the postmaster's copy.)
	 */
	split_opts(av, &ac, ExtraOptions);

	/* Tell the backend what protocol the frontend is using. */
	sprintf(protobuf, "-v%u", port->proto);
	av[ac++] = protobuf;

	/*
	 * Tell the backend it is being called from the postmaster, and which
	 * database to use.  -p marks the end of secure switches.
	 */
	av[ac++] = "-p";

	StrNCpy(dbbuf, port->database, ARGV_SIZE);
	av[ac++] = dbbuf;

	/*
	 * Pass the (insecure) option switches from the connection request.
	 */
	StrNCpy(optbuf, port->options, ARGV_SIZE);
	split_opts(av, &ac, optbuf);

	/*
	 * Pass the (insecure) debug output file request.
	 *
	 * NOTE: currently, this is useless code, since the backend will not
	 * honor an insecure -o switch.  I left it here since the backend
	 * could be modified to allow insecure -o, given adequate checking
	 * that the specified filename is something safe to write on.
	 */
	if (port->tty[0])
	{
		StrNCpy(ttybuf, port->tty, ARGV_SIZE);
		av[ac++] = "-o";
		av[ac++] = ttybuf;
	}

	av[ac] = (char *) NULL;

	/*
	 * Release postmaster's working memory context so that backend can
	 * recycle the space.  Note this does not trash *MyProcPort, because
	 * ConnCreate() allocated that space with malloc() ... else we'd need
	 * to copy the Port data here.
	 */
	MemoryContextSwitchTo(TopMemoryContext);
	MemoryContextDelete(PostmasterContext);
	PostmasterContext = NULL;

	/*
	 * Debug: print arguments being passed to backend
	 */
	if (DebugLvl > 1)
	{
		fprintf(stderr, "%s child[%d]: starting with (",
				progname, MyProcPid);
		for (i = 0; i < ac; ++i)
			fprintf(stderr, "%s ", av[i]);
		fprintf(stderr, ")\n");
	}

	return (PostgresMain(ac, av, real_argc, real_argv, port->user));
}

/*
 * ExitPostmaster -- cleanup
 *
 * Do NOT call exit() directly --- always go through here!
 */
static void
ExitPostmaster(int status)
{
	/* should cleanup shared memory and kill all backends */

	/*
	 * Not sure of the semantics here.	When the Postmaster dies, should
	 * the backends all be killed? probably not.
	 *
	 * MUST		-- vadim 05-10-1999
	 */
	if (ServerSock_INET != INVALID_SOCK)
		StreamClose(ServerSock_INET);
	ServerSock_INET = INVALID_SOCK;
#ifdef HAVE_UNIX_SOCKETS
	if (ServerSock_UNIX != INVALID_SOCK)
		StreamClose(ServerSock_UNIX);
	ServerSock_UNIX = INVALID_SOCK;
#endif

	proc_exit(status);
}

static void
dumpstatus(SIGNAL_ARGS)
{
	Dlelem	   *curr;

	PG_SETMASK(&BlockSig);

	curr = DLGetHead(PortList);
	while (curr)
	{
		Port	   *port = DLE_VAL(curr);

		fprintf(stderr, "%s: dumpstatus:\n", progname);
		fprintf(stderr, "\tsock %d\n", port->sock);
		curr = DLGetSucc(curr);
	}
}

/*
 * CharRemap
 */
static char
CharRemap(long int ch)
{

	if (ch < 0)
		ch = -ch;

	ch = ch % 62;
	if (ch < 26)
		return 'A' + ch;

	ch -= 26;
	if (ch < 26)
		return 'a' + ch;

	ch -= 26;
	return '0' + ch;
}

/*
 * RandomSalt
 */
static void
RandomSalt(char *salt)
{
	long		rand = PostmasterRandom();

	*salt = CharRemap(rand % 62);
	*(salt + 1) = CharRemap(rand / 62);
}

/*
 * PostmasterRandom
 */
static long
PostmasterRandom(void)
{
	static bool initialized = false;

	if (!initialized)
	{
		Assert(random_seed != 0);
		srandom(random_seed);
		initialized = true;
	}

	return random() ^ random_seed;
}

/*
 * Count up number of child processes.
 */
static int
CountChildren(void)
{
	Dlelem	   *curr;
	Backend    *bp;
	int			mypid = getpid();
	int			cnt = 0;

	for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
	{
		bp = (Backend *) DLE_VAL(curr);
		if (bp->pid != mypid)
			cnt++;
	}
	if (CheckPointPID != 0)
		cnt--;
	return cnt;
}

#ifdef USE_SSL
/*
 * Initialize SSL library and structures
 */
static void
InitSSL(void)
{
	char		fnbuf[2048];

	SSL_load_error_strings();
	SSL_library_init();
	SSL_context = SSL_CTX_new(SSLv23_method());
	if (!SSL_context)
	{
		fprintf(stderr, "Failed to create SSL context: %s\n", ERR_reason_error_string(ERR_get_error()));
		ExitPostmaster(1);
	}
	snprintf(fnbuf, sizeof(fnbuf), "%s/server.crt", DataDir);
	if (!SSL_CTX_use_certificate_file(SSL_context, fnbuf, SSL_FILETYPE_PEM))
	{
		fprintf(stderr, "Failed to load server certificate (%s): %s\n", fnbuf, ERR_reason_error_string(ERR_get_error()));
		ExitPostmaster(1);
	}
	snprintf(fnbuf, sizeof(fnbuf), "%s/server.key", DataDir);
	if (!SSL_CTX_use_PrivateKey_file(SSL_context, fnbuf, SSL_FILETYPE_PEM))
	{
		fprintf(stderr, "Failed to load private key file (%s): %s\n", fnbuf, ERR_reason_error_string(ERR_get_error()));
		ExitPostmaster(1);
	}
	if (!SSL_CTX_check_private_key(SSL_context))
	{
		fprintf(stderr, "Check of private key failed: %s\n", ERR_reason_error_string(ERR_get_error()));
		ExitPostmaster(1);
	}
}

#endif

static pid_t
SSDataBase(int xlop)
{
	pid_t		pid;
	Backend	   *bn;

	fflush(stdout);
	fflush(stderr);

	if ((pid = fork()) == 0)	/* child */
	{
		char	   *av[ARGV_SIZE * 2];
		int			ac = 0;
		char		nbbuf[ARGV_SIZE];
		char		dbbuf[ARGV_SIZE];
		char		xlbuf[ARGV_SIZE];

		/* Lose the postmaster's on-exit routines and port connections */
		on_exit_reset();

		if (NetServer)
			StreamClose(ServerSock_INET);
		ServerSock_INET = INVALID_SOCK;
#ifdef HAVE_UNIX_SOCKETS
		StreamClose(ServerSock_UNIX);
		ServerSock_UNIX = INVALID_SOCK;
#endif

		av[ac++] = "postgres";

		av[ac++] = "-d";

		sprintf(nbbuf, "-B%u", NBuffers);
		av[ac++] = nbbuf;

		sprintf(xlbuf, "-x %d", xlop);
		av[ac++] = xlbuf;

		av[ac++] = "-p";

		StrNCpy(dbbuf, "template1", ARGV_SIZE);
		av[ac++] = dbbuf;

		av[ac] = (char *) NULL;

		optind = 1;

		pqsignal(SIGQUIT, SIG_DFL);
#ifdef HAVE_SIGPROCMASK
		sigdelset(&BlockSig, SIGQUIT);
#else
		BlockSig &= ~(sigmask(SIGQUIT));
#endif
		PG_SETMASK(&BlockSig);

		BootstrapMain(ac, av);
		ExitPostmaster(0);
	}

	/* in parent */
	if (pid < 0)
	{
		fprintf(stderr, "%s Data Base: fork failed: %s\n",
				((xlop == BS_XLOG_STARTUP) ? "Startup" : 
					((xlop == BS_XLOG_CHECKPOINT) ? "CheckPoint" :
						"Shutdown")), strerror(errno));
		ExitPostmaster(1);
	}

	if (xlop != BS_XLOG_CHECKPOINT)
		return(pid);

	if (!(bn = (Backend *) calloc(1, sizeof(Backend))))
	{
		fprintf(stderr, "%s: CheckPointDataBase: malloc failed\n",
				progname);
		ExitPostmaster(1);
	}

	bn->pid = pid;
	bn->cancel_key = 0;
	DLAddHead(BackendList, DLNewElem(bn));

	return (pid);
}


/*
 * Create the opts file
 */
static bool
CreateOptsFile(int argc, char *argv[])
{
	char    fullprogname[MAXPGPATH];
	char   *filename;
	FILE   *fp;
	unsigned i;

	if (FindExec(fullprogname, argv[0], "postmaster") == -1)
		return false;

	filename = palloc(strlen(DataDir) + 20);
	sprintf(filename, "%s/postmaster.opts", DataDir);

	fp = fopen(filename, "w");
	if (fp == NULL)
	{
		fprintf(stderr, "%s: cannot create file %s: %s\n", progname,
				filename, strerror(errno));
		return false;
	}

	fprintf(fp, "%s", fullprogname);
	for (i = 1; i < argc; i++)
		fprintf(fp, " '%s'", argv[i]);
	fputs("\n", fp);

	if (ferror(fp))
	{
		fprintf(stderr, "%s: writing file %s failed\n", progname, filename);
		fclose(fp);
		return false;
	}

	fclose(fp);
	return true;
}