3
* A simple wrapper on top of fork(). This does not handle the
4
* EXEC_BACKEND case; it might be extended to do so, but it would be
5
* considerably more complex.
7
* Copyright (c) 1996-2011, PostgreSQL Global Development Group
10
* src/backend/postmaster/fork_process.c
13
#include "postmaster/fork_process.h"
23
* Wrapper for fork(). Return values are the same as those for fork():
24
* -1 if the fork failed, 0 in the child process, and the PID of the
25
* child in the parent process.
33
struct itimerval prof_itimer;
37
* Flush stdio channels just before fork, to avoid double-output problems.
38
* Ideally we'd use fflush(NULL) here, but there are still a few non-ANSI
39
* stdio libraries out there (like SunOS 4.1.x) that coredump if we do.
40
* Presently stdout and stderr are the only stdio output channels used by
41
* the postmaster, so fflush'ing them should be sufficient.
49
* Linux's fork() resets the profiling timer in the child process. If we
50
* want to profile child processes then we need to save and restore the
51
* timer setting. This is a waste of time if not profiling, however, so
52
* only do it if commanded by specific -DLINUX_PROFILE switch.
54
getitimer(ITIMER_PROF, &prof_itimer);
60
/* fork succeeded, in child */
62
setitimer(ITIMER_PROF, &prof_itimer, NULL);
66
* By default, Linux tends to kill the postmaster in out-of-memory
67
* situations, because it blames the postmaster for the sum of child
68
* process sizes *including shared memory*. (This is unbelievably
69
* stupid, but the kernel hackers seem uninterested in improving it.)
70
* Therefore it's often a good idea to protect the postmaster by
71
* setting its oom_adj value negative (which has to be done in a
72
* root-owned startup script). If you just do that much, all child
73
* processes will also be protected against OOM kill, which might not
74
* be desirable. You can then choose to build with LINUX_OOM_ADJ
75
* #defined to 0, or some other value that you want child processes to
81
* Use open() not stdio, to ensure we control the open flags. Some
82
* Linux security environments reject anything but O_WRONLY.
84
int fd = open("/proc/self/oom_adj", O_WRONLY, 0);
86
/* We ignore all errors */
91
snprintf(buf, sizeof(buf), "%d\n", LINUX_OOM_ADJ);
92
(void) write(fd, buf, strlen(buf));
96
#endif /* LINUX_OOM_ADJ */