Postgresql postmaster pid windows

«FATAL: заблокировать файл» postmaster.pid «уже существует»

Я только что переустановил Postgres через brew install postgres

Я побежал, initdb /usr/local/var/postgres -E utf8 но получил это:

Итак, я rm -rf открыл папку postgres и снова запустил ее:

он сказал, что все в порядке:

Итак, я выполнил эту команду и получил:

Теперь, когда я смотрю на монитор активности, я вижу 6 случаев пост-прогресса.

Как я могу это исправить?

Объявление о государственной службе: никогда не удаляйте postmaster.pid . В самом деле. Отличный способ получить повреждение данных.

У вас уже был установлен PostgreSQL, и вы удалили каталог с данными, не останавливая работающий сервер. Итак, теперь у вас есть несколько потерянных серверных процессов PostgreSQL, которые управляют удаленными файлами данных, поэтому они больше не доступны в файловой системе и будут полностью удалены, когда последний дескриптор открытого файла для них будет закрыт. Вы не можете использовать, pg_ctl чтобы выключить сервер, как обычно, потому что вы удалили кластерный datadir, поэтому вы должны просто завершить процессы. Убейте почтмейстера ( не используйте kill -9 , подойдет обычное убийство), а остальные тоже отключатся.

После этого вы сможете запустить новый сервер в datadir со свежими initdb данными.

Весьма вероятно, что вы столкнетесь с конфликтами в будущем, если не удалите другую более старую версию PostgreSQL.

В двух словах:

Запишите номер в первой строке, который является pid почтмейстера.

Убедитесь, ps что pid — это почтмейстер postgres.

Завершите процесс postmaster с помощью следующей команды, заменив ‘PID’ на номер, который вы записали. Опять же, не используйте kill -9 или kill -KILL просто используйте простой kill , то есть SIGTERM :

Обсуждение: FATAL: lock file «postmaster.pid» already exists

FATAL: lock file «postmaster.pid» already exists

On Windows 2008, sometimes the server fails to start due to an existing «postmaster.pid’ file.

I tried rebooting a few times and even force shutting down the server, and it started up fine.
It seems to be a race-condition of sorts in the code that detects whether the process with PID
in the file is running or not.

Does any one have this same problem? Any way to fix it besides removing the PID file
manually each time the server complains about this?

Re: FATAL: lock file «postmaster.pid» already exists

Re: FATAL: lock file «postmaster.pid» already exists

On 8 May 2012, at 24:34, deepak wrote:

> Hi,
>
> On Windows 2008, sometimes the server fails to start due to an existing «postmaster.pid’ file.
>
> I tried rebooting a few times and even force shutting down the server, and it started up fine.
> It seems to be a race-condition of sorts in the code that detects whether the process with PID
> in the file is running or not.

No, it means that postgres wasn’t shut down properly when Windows shut down. Removing the pid-file is one of the last things the shut-down procedure does. The file is used to prevent 2 instances of the same server running on the same data-directory.

If it’s a race-condition, it’s probably one in Microsoft’s shutdown code. I’ve seen similar problems with Outlook mailboxes on a network directory; Windows unmounts the remote file-systems before Outlook finished updating its files under that mount point, so Outlook throws an error message and Windows doesn’t shut down because of that.

I don’t suppose that pid-file is on a remote file-system?

> Does any one have this same problem? Any way to fix it besides removing the PID file
> manually each time the server complains about this?

You could probably script removal of the pid file if its creation date is before the time the system started booting up.

Thanks, it looks like the code already seems to overwrite an old pid file if no other process is using it (if I understand the code correctly, it just echoes a byte onto a pipe to detect this).

Читайте также:  Кисти для paint windows

Still, I can’t see under what conditions this occurs, but I have seen it happen a couple of times, just that I don’t know how to predictably reproduce the problem.

Re: FATAL: lock file «postmaster.pid» already exists

We could reproduce the start-up problem on Windows 2003. After a reboot, postmaster, in its start-up sequence cleans up old temporary files, and this step used to take several minutes (a little over 4 minutes), delaying the writing of line 6 onwards into the PID file. This delay caused pg_ctl to timeout, leaving behind an orphaned postgres.exe process (which eventually forks off many other postgres.exe processes). But since pg_ctl itself isn’t running after the timeout, Windows thinks the service isn’t running. A subsequent attempt to start the service using pg_ctl now complains about the existing lock file still being used by one of the postgres.exe processes that was spawned before.

We have observed conclusively that file system cache is coming into play. We tested the scenario in which a reboot was followed by navigating the file system under the data directory using «find» Cygwin command, following which there was «no» timeout for pg_ctl and the server started up fine, suggesting that the clean up is way faster when the file system is cached.

Any ideas on fixing this start-up delay in postmaster?

Could the task of cleanup move elsewhere, specifically to somewhere after the writing of PID file is complete so that pg_ctl doesn’t timeout?

Any other suggestions for working around this problem?

On 8 May 2012, at 24:34, deepak wrote:

> Hi,
>
> On Windows 2008, sometimes the server fails to start due to an existing «postmaster.pid’ file.
>
> I tried rebooting a few times and even force shutting down the server, and it started up fine.
> It seems to be a race-condition of sorts in the code that detects whether the process with PID
> in the file is running or not.

No, it means that postgres wasn’t shut down properly when Windows shut down. Removing the pid-file is one of the last things the shut-down procedure does. The file is used to prevent 2 instances of the same server running on the same data-directory.

If it’s a race-condition, it’s probably one in Microsoft’s shutdown code. I’ve seen similar problems with Outlook mailboxes on a network directory; Windows unmounts the remote file-systems before Outlook finished updating its files under that mount point, so Outlook throws an error message and Windows doesn’t shut down because of that.

I don’t suppose that pid-file is on a remote file-system?

> Does any one have this same problem? Any way to fix it besides removing the PID file
> manually each time the server complains about this?

You could probably script removal of the pid file if its creation date is before the time the system started booting up.

Thanks, it looks like the code already seems to overwrite an old pid file if no other process is using it (if I understand the code correctly, it just echoes a byte onto a pipe to detect this).

Still, I can’t see under what conditions this occurs, but I have seen it happen a couple of times, just that I don’t know how to predictably reproduce the problem.

FATAL: could not create lock file “postmaster.pid”: Permission denied

I receive error

when trying to execute command

Full rights for postgres user to D:\, D:\Program Files\, D:\Program Files\PostgreSQL\ and D:\Program Files\PostgreSQL\8.3\data are set. What else I need to do?

5 Answers 5

I set full access to D:\Program Files\PostgreSQL\8.3\data to Users group and now it works. Detail are at http://forumserver.twoplustwo.com/114/pokertracker/cant-connect-db-422617/ (last post).

You need to ensure that the user postgres has write permission to the postgres data_directory configured in postgresql.conf file. In my case /var/lib/postgresql/9.5/main/ if not add permission with:

You have to make ensure that the user postgres has right to write & execute /var/run/postgresql

I had this issue due to installing postgres-xc and the solution was to remove it.

pg_ctl is the most common (and recommended) way used to start/stop/etc postgres.

For some reason it was not part of my postgres install.
After duckduckgo’ing a little, I installed postgre-xc which includes pg_ctl.
postgres-xc changed the owner of /var/run/postgresql from postgres to postgres-xc.
This caused lots of headaches and warnings about being unable to lock the pid file.

So, I removed postgres-xc (and reverted the owner of /var/run/postgresql to postgres).

Instead of using pg_ctl, I control postgres using

Читайте также:  Обновить файрвол windows 10

What’s a data directory and postmaster.pid issue #395

Comments

MtnBiker commented Jun 12, 2017

I’m having a Postgres.app 9.5 problem and the https://postgresapp.com/documentation/troubleshooting.html refers to data directory which I’m unfamiliar with. Long time macOS user. I found this searching for postmaster.pid which is identified as a problem. When I found this file it was dated 1.5 years ago, so unlikely its corrupted.

The text was updated successfully, but these errors were encountered:

jakob commented Jun 12, 2017

The data directory of your PostgreSQL server can be changed in the settings. The default data dir for version 9.5 is in

postmaster.pid stores the pid (process id) of the main postgres process. If it was created 1.5 years ago you either haven’t restarted PostgreSQL in a very long time, or the server was shut down ungracefully and wasn’t started in a long time.

You can delete the postmaster.pid file if you make sure that no process named postgres or postmaster is running anymore.

MtnBiker commented Jun 12, 2017 •

Thanks jakob. The comment had more to do with the documentation— data directory is not a term known to me as a Mac user. Application Support I do know about. Is there a better place to comment on the documentation?

Ah, the postmaster.pid I found was another one: /usr/local/var/postgres/postmaster.pid, maybe from some other attempted installation of Postgres when I was getting started with it. In any case what got me going was deleting another file: com.postgresapp.Postgres2LoginHelper.plist . Found that via Stackoverflow. All due to a flaky dock for my laptop which is now awaiting an RWA.

jakob commented Jun 13, 2017

Good point. It would be good to write some documentation on the data directory, since that is something that is often unclear to people new to PostgreSQL. (I remember that it was unclear to me as well).

Then we should probably link to that page any time the data directory is mentioned in the docs.

jerry-shao commented Jan 23, 2018

Open Postgres GUI app, click server settings, you will see the data path.

By default, it may stored at /Users/USERNAME/Library/Application Support/Postgres/var-POSTGRES_VERSION , change USERNAME and POSTGRES_VERSION to yours.

jcdavison commented Jun 1, 2018

@jerry-shao crazy when I find a year old post that solves my problems so smartly, and it was weird, my machine reset itself while I was in restroom and I came back to this prob ⚡️

Postgresql postmaster pid windows

При установке двоичных пакетов в системах Linux базы данных по умолчанию располагаются в каталоге /var/lib/pgpro/std-11/data , если явно не будет задан другой каталог. За подробностями обратитесь к Разделу 16.1.

Чтобы кто-либо смог обратиться к базе данных, необходимо сначала запустить сервер баз данных. Программа сервера называется postgres . Для работы программа postgres должна знать, где найти данные, которые она будет использовать. Указать это местоположение позволяет параметр -D . Таким образом, проще всего запустить сервер, выполнив команду:

в результате которой сервер продолжит работу в качестве процесса переднего плана. Запускать эту команду следует под именем учётной записи Postgres Pro . Без параметра -D сервер попытается использовать каталог данных, указанный в переменной окружения PGDATA . Если и эта переменная не определена, сервер не будет запущен.

Однако обычно лучше запускать postgres в фоновом режиме. Для этого можно применить обычный синтаксис, принятый в оболочке Unix:

Важно где-либо сохранять информацию, которую выводит сервер в каналы stdout и stderr , как показано выше. Это полезно и для целей аудита, и для диагностики проблем. (Более глубоко работа с файлами журналов рассматривается в Разделе 23.3.)

Программа postgres также принимает несколько других параметров командной строки. За дополнительными сведениями обратитесь к справочной странице postgres и к следующей Главе 18.

Такой вариант запуска довольно быстро может оказаться неудобным. Поэтому для упрощения подобных задач предлагается вспомогательная программа pg_ctl . Например:

запустит сервер в фоновом режиме и направит выводимые сообщения сервера в указанный файл журнала. Параметр -D для неё имеет то же значение, что и для программы postgres . С помощью pg_ctl также можно остановить сервер.

Обычно возникает желание, чтобы сервер баз данных сам запускался при загрузке операционной системы. Скрипты автозапуска для разных систем разные, но в составе Postgres Pro предлагается несколько типовых скриптов в каталоге contrib/start-scripts . Для установки такого скрипта в систему требуются права root.

В различных системах приняты разные соглашения о порядке запуска служб в процессе загрузки. Во многих системах для этого используется файл /etc/rc.local или /etc/rc.d/rc.local . В других применяются каталоги init.d или rc.d . Однако при любом варианте запускаться сервер должен от имени пользователя Postgres Pro , но не root или какого-либо другого пользователя. Поэтому команду запуска обычно следует записывать в форме su postgres -c ‘. ‘ . Например:

Читайте также:  Asrock uefi setup utility как переустановить windows с флешки

Ниже приведены более конкретные предложения для нескольких основных ОС. (Вместо указанных нами шаблонных значений необходимо подставить правильный путь к каталогу данных и фактическое имя пользователя.)

Для запуска во FreeBSD воспользуйтесь файлом contrib/start-scripts/freebsd в дереве исходного кода Postgres Pro .

В OpenBSD , добавьте в файл /etc/rc.local следующие строки:

В системах Linux вы можете либо добавить

в /etc/rc.d/rc.local или в /etc/rc.local , либо воспользоваться файлом contrib/start-scripts/linux в дереве исходного кода Postgres Pro .

Используя systemd , вы можете применить следующий файл описания службы (например, /etc/systemd/system/postgresql.service ):

Для использования Type=notify требуется, чтобы сервер был скомпилирован с указанием configure —with-systemd .

Особого внимания заслуживает значение тайм-аута. На момент написания этой документации по умолчанию в systemd принят тайм-аут 90 секунд, так что процесс, не сообщивший о своей готовности за это время, будет уничтожен. Но серверу Postgres Pro при запуске может потребоваться выполнить восстановление после сбоя, так что переход в состояние готовности может занять гораздо больше времени. Предлагаемое значение 0 отключает логику тайм-аута.

В NetBSD можно использовать скрипт запуска для FreeBSD или для Linux , в зависимости от предпочтений.

В Solaris , создайте файл с именем /etc/init.d/postgresql , содержащий следующую стоку:

Затем создайте символическую ссылку на него в каталоге /etc/rc3.d с именем S99postgresql .

17.3.1. Сбои при запуске сервера

Есть несколько распространённых причин, по которым сервер может не запуститься. Чтобы понять, чем вызван сбой, просмотрите файл журнала сервера или запустите сервер вручную (не перенаправляя его потоки стандартного вывода и ошибок) и проанализируйте выводимые сообщения. Ниже мы рассмотрим некоторые из наиболее частых сообщений об ошибках более подробно.

Это обычно означает именно то, что написано: вы пытаетесь запустить сервер на том же порту, на котором уже работает другой. Однако, если сообщение ядра не Address already in use или подобное, возможна и другая проблема. Например, при попытке запустить сервер с номером зарезервированного порта будут выданы такие сообщения:

может означать, что установленный для вашего ядра предельный размер разделяемой памяти слишком мал для рабочей области, которую пытается создать Postgres Pro (в данном примере 4011376640 байт). Возможно также, что в вашем ядре вообще отсутствует поддержка разделяемой памяти в стиле System-V. В качестве временного решения можно попытаться запустить сервер с меньшим числом буферов (shared_buffers), но в итоге вам, скорее всего, придётся переконфигурировать ядро и увеличить допустимый размер разделяемой памяти. Вы также можете увидеть это сообщение при попытке запустить несколько серверов на одном компьютере, если запрошенный ими объём разделяемой памяти в сумме превышает этот предел.

не означает, что у вас закончилось место на диске. Это значит, что установленное в вашем ядре предельное число семафоров System V меньше, чем количество семафоров, которое пытается создать Postgres Pro . Как и в предыдущем случае можно попытаться обойти эту проблему, запустив сервер с меньшим числом допустимых подключений (max_connections), но в конце концов вам придётся увеличить этот предел в ядре.

Если вы получаете ошибку « illegal system call » (неверный системный вызов), то, вероятнее всего, ваше ядро вовсе не поддерживает разделяемую память или семафоры. В этом случае вам остаётся только переконфигурировать ядро и включить их поддержку.

17.3.2. Проблемы с подключениями клиентов

Хотя ошибки подключений, возможные на стороне клиента, довольно разнообразны и зависят от приложений, всё же несколько проблем могут быть связаны непосредственно с тем, как был запущен сервер. Описание ошибок, отличных от описанных ниже, следует искать в документации соответствующего клиентского приложения.

Это общая проблема « я не могу найти сервер и начать взаимодействие с ним » . Показанное выше сообщение говорит о попытке установить подключение по TCP/IP. Очень часто объясняется это тем, что сервер просто забыли настроить для работы по протоколу TCP/IP.

Кроме того, при попытке установить подключение к локальному серверу через Unix-сокет можно получить такое сообщение:

Путь в последней строке помогает понять, к правильному ли адресу пытается подключиться клиент. Если сервер на самом деле не принимает подключения по этому адресу, обычно выдаётся сообщение ядра Connection refused (В соединении отказано) или No such file or directory (Нет такого файла или каталога), приведённое выше. (Важно понимать, что Connection refused в данном контексте не означает, что сервер получил запрос на подключение и отверг его. В этом случае были бы выданы другие сообщения, например, показанные в Разделе 19.15.) Другие сообщения об ошибках, например Connection timed out (Тайм-аут соединения) могут сигнализировать о более фундаментальных проблемах, например, о нарушениях сетевых соединений.

Оцените статью