Windows service error 1063

Trying to develop my first windows service, and I'm debugging in windows 7 MS VC++ 10.0. As soon as it calls, StartServiceCtrlDispatcher(), I get an error 1063 and it says Access is Denied. I am

Trying to develop my first windows service, and I’m debugging in windows 7 MS VC++ 10.0. As soon as it calls, StartServiceCtrlDispatcher(), I get an error 1063 and it says Access is Denied. I am administrator, how exactly do I get passed this? I’m new to services. Thanks. Code:

// For WinXp, don't forget to link to
// Advapi32.lib library if needed...

#define _WIN32_WINNT 0x0501

#include <windows.h>

#include <stdio.h>
#include <tchar.h>

// Prototypes, just empty skeletons...

void SvcDebugOut(LPSTR String, DWORD Status);
void  WINAPI MyServiceCtrlHandler(DWORD opcode);
void  MyServiceStart(DWORD argc, LPTSTR *argv);
DWORD MyServiceInitialization(DWORD argc, LPTSTR *argv, DWORD *specificError);

void main() 
{

       // Using 2-D array as a table...

       // The name of a service to be run in this service process - "MyService",

       // The function as the starting point for a service - MyServiceStart or

       // a pointer to a ServiceMain() function...

       // The members of the last entry in the table must have NULL values

       // to designate the end of the table...

       SERVICE_TABLE_ENTRY  DispatchTable[] = {{_TEXT("MyService"), (LPSERVICE_MAIN_FUNCTION)MyServiceStart}, {NULL, NULL}};
   if (!StartServiceCtrlDispatcher(DispatchTable))
       SvcDebugOut("StartServiceCtrlDispatcher() failed, error: %dn", GetLastError());
   else
       printf("StartServiceCtrlDispatcher() looks OK.n");
   return;
} 

// ==========================================================================
// Prototype definitions...just skeletons here...
void  WINAPI MyServiceCtrlHandler(DWORD opcode)
{
       // Service control information here...
       return;
}

void  MyServiceStart(DWORD argc, LPTSTR *argv)
{
       // Starting service information here...
       return;
}



DWORD MyServiceInitialization(DWORD argc, LPTSTR *argv, DWORD *specificError)
{
       // Service initialization information here...
       return 0;
}

// Very simple info to the standard output...
void SvcDebugOut(LPSTR String, DWORD Status)
{
   CHAR  Buffer[1024];
   printf("In SvcDebugOut() lol!n");
   if (strlen(String) < 1000)
   {
      sprintf(Buffer, String, Status);
      OutputDebugStringA(Buffer);
   }
   else 
      printf("String too long...n");
   return;
}

  • Remove From My Forums
  • Question

  • ‘m trying to start and stop the windows service programatically using a notify tray icon. The service and the System Tray Icon App can talk over Named pipes IPC. So, I took this example from msdn and
    added IPC schemes to it. This service on starting, installs himself (create service method) successfully. Now I don’t call him to start from services.msc.

    Instead the Tray Icon pings the service and service pongs back. Then, the Tray ICon sends a start command. Upon receiving the start command, the service has to kick off him self and start running.

    On Start Request from tray icon, I’m calling run service method in the example, which has the service table and service control dispatcher in it (I assume, the service control dispatcher will trigger a call onstart method from windows). But the service control
    dispatcher return the 1063 error. I tried with admin privileges and moving him to secure account etc., nothing worked.

    Can someone help me where am I going wrong?

    Attached is the source code
    for reference.

    Thanks.

    • Moved by

      Wednesday, May 7, 2014 7:42 AM
      for a better support

Answers

  • Hello,

    For C++ Windows Service Error 1063, you can check this link:

    http://stackoverflow.com/a/17378034

    Services run under the account that is specified in the properties of their registration. It might not be the same to account that registers the service or starts it. Reads about this.

    Many services run under «Network service» account that has very limited capabilities. This makes sense because many services process requests that come from the network. This is why «Network service» was selected by Microsoft as default.

    Hope it to be helpful.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.

    Click
    HERE to participate the survey.

    • Edited by
      Fred Bao
      Thursday, May 8, 2014 7:50 AM
    • Marked as answer by
      Marvin_Guo
      Wednesday, May 14, 2014 8:33 AM

Содержание

  1. Start service error 1063
  2. Start service error 1063
  3. Answered by:
  4. Question
  5. Solved: Suggestions To Fix Startservicectrldispatcher Failed With Error Code 1063
  6. PC running slow?
  7. PC running slow?
  8. Not The Answer You’re Looking For? Browse Other Requests Marked With The Windows Icon Winapi Windows-services, Or Ask Your Own Question.
  9. Start service error 1063
  10. Answered by:
  11. Question
  12. Re: Error code 1063

Start service error 1063

Здравствуйте, , Вы писали:

А>Чем вызывывается и что означает ошибка 1063 (The service process could not connect to the service controller) при запуске сервиса? Как с этим бороться?

А на код основных функций сервиса можно взглянуть? Точка входа, ServiceMain(), Handler().

ICQ#116846877
In Windows, there’s always a catch… © Paul DiLascia

От: Аноним
Дата: 04.10.04 17:56
Оценка:

Здравствуйте, SchweinDeBurg, Вы писали:

SDB>А на код основных функций сервиса можно взглянуть? Точка входа, ServiceMain(), Handler().

Запуск из командной строки без аргументов, ServiceMain() не вызывается.

От: Аноним
Дата: 04.10.04 18:06
Оценка:

Здравствуйте, Аноним, Вы писали:

А>Здравствуйте, SchweinDeBurg, Вы писали:

SDB>>А на код основных функций сервиса можно взглянуть? Точка входа, ServiceMain(), Handler().

Все, вопрос снят. Туплю блин.
Думаю что когда сервис стартует из командной строки, CSM-менеджер не открыт, поэтому StartServiceCtrlDispatcher() возвращает ошибку.

Источник

Start service error 1063

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

‘m trying to start and stop the windows service programatically using a notify tray icon. The service and the System Tray Icon App can talk over Named pipes IPC. So, I took this example from msdn and added IPC schemes to it. This service on starting, installs himself (create service method) successfully. Now I don’t call him to start from services.msc.

Instead the Tray Icon pings the service and service pongs back. Then, the Tray ICon sends a start command. Upon receiving the start command, the service has to kick off him self and start running.

On Start Request from tray icon, I’m calling run service method in the example, which has the service table and service control dispatcher in it (I assume, the service control dispatcher will trigger a call onstart method from windows). But the service control dispatcher return the 1063 error. I tried with admin privileges and moving him to secure account etc., nothing worked.

Can someone help me where am I going wrong?

Источник

Solved: Suggestions To Fix Startservicectrldispatcher Failed With Error Code 1063

Table of Contents

PC running slow?

Over the past few weeks, some users have reported startservicectrldispatcher crashing with error code 1063. g.According to the list of system error codes, error 1063 is ERROR_FAILED_SERVICE_CONTROLLER_CONNECT. According to the documentation for StartServiceCtrlDispatcher, this skill error is returned when you try to launch this application as a console product (that is, double-click the executable or start debugging from within Visual Studio).

Visited 23k times

I see a strange error in a good Windows utility. My service calls StartServiceCtrlDispatcher () at the very beginning of main () , but sometimes also calls 1063 (ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) .

I know this error only occurs if the user immediately launches the program. (like a console program). But this is currently not the case. I added a swap check to the parent process of some utility when this error occurs and tells services.exe that it is the parent process (I think it’s safe to assume that SCM started my program successfully).

Unfortunately this error does not repeat itself on my development machine and I cannot debug it myself, but the error reported in the logs recorded on user systems is:

  • Only a few% of more or less all users of this program face this problem.
  • Although the nightmare does happen, it doesn’t seem to repeat itself. Next time the service is successfully deployed.
  • In this case, the problem is StartServiceCtrlDispatcher () persists for a second and then returns due to an error.

PC running slow?

ASR Pro is the ultimate solution for your PC repair needs! Not only does it swiftly and safely diagnose and repair various Windows issues, but it also increases system performance, optimizes memory, improves security and fine tunes your PC for maximum reliability. So why wait? Get started today!

Has anyone seen similar errors? So technically, what was the reason for each of our mistakes?

34.6 thousand 2727 gold badges 157157 jewelry badges 313313 bronze badges

I wanted to know on May 26, 15, 16:30.

279 11 of your unwanted watch badges 22 silver badges 77 bronze badges

Not The Answer You’re Looking For? Browse Other Requests Marked With The Windows Icon Winapi Windows-services, Or Ask Your Own Question.

As you can already see fromsome lack of response and all of this in search engines such as Yahoo, the problem is infrequent. Believe me, your problem lies with your service, and this one, in particular, is in the code that runs from the very beginning of the process to StartServiceCtrlDispatcher () , and most likely this usually requires some form distortion of the system resources. most likely heap or HANDLE .

You may be sorry to hear this, but I am not leaving you with a magical answer to your concerns. Instead, I suggest troubleshooting.

Microsoft’s app is invaluable for detecting damage. I suggest you:

  1. Install it to develop your favorite computer.
  2. Add your service exe file.
  3. For the first time only, select Basics Heaps .
  4. Click Save. It doesn’t matter if you leave Verifier open. Your application will be open.
  5. Start the service multiple times.
  6. If the concept fails, it is debugged and the failure indicates your problem.
  7. If it fails, do not add Basics Handles . Basics Heaps , on the other hand, can be calledvans “false positives” – errors in the voucher code that do not cause much harm. Either way, since you’re usually on the hunt, you’d better fix whatever you find. I’m most worried about the double HANDLE exception or something similar. If you free the HANDLE service handler from corruption, it can definitely lead to a problem.
  8. If it still doesn’t crash, you can try other strategies in Basics * , but I’m not interested if that helps.
  9. At this point, you want to view the code between the main () and StartServiceCtrlDispatcher () functions of the program, as well as any global constructors you have. Check for obstructions, overflows and errors in HANDLE .
  10. The next step may be to install Application Verifier on the client computer. It doesn’t hurt too much, sometimes I get sick when I can’t find the guilt myself.

answered Jun 8 15 at 21:37

7.237 22 white gold badges 3,434 silver badges 4040 bronze badges

TIP. I used _wfopen / fwrite / fclose to log some messages. Somehow 183 got started and internally this error was assigned to 1063. I deleted the job and it started working fine, nothing for the location. Every little mistake can lead anyone to this. If you start with services and run the list, you will see a salary error (183 in my case).

Источник

Start service error 1063

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

‘m trying to start and stop the windows service programatically using a notify tray icon. The service and the System Tray Icon App can talk over Named pipes IPC. So, I took this example from msdn and added IPC schemes to it. This service on starting, installs himself (create service method) successfully. Now I don’t call him to start from services.msc.

Instead the Tray Icon pings the service and service pongs back. Then, the Tray ICon sends a start command. Upon receiving the start command, the service has to kick off him self and start running.

On Start Request from tray icon, I’m calling run service method in the example, which has the service table and service control dispatcher in it (I assume, the service control dispatcher will trigger a call onstart method from windows). But the service control dispatcher return the 1063 error. I tried with admin privileges and moving him to secure account etc., nothing worked.

Can someone help me where am I going wrong?

Источник

Re: Error code 1063

From: «Magnus Hagander»
To: «Robert Fitzpatrick»
, «PostgreSQL»

Subject: Re: Error code 1063 Date: 2006-07-12 12:13:51 Message-ID: 6BCB9D8A16AC4241919521715F4D8BCEA0FAEC@algol.sollentuna.se Views: Raw Message | Whole Thread | Download mbox | Resend email Thread: Lists: pgsql-general

> We have PostgreSQL 8.1 running on Windows 2000 for a few
> weeks now, when we try to start the service, it could not
> start claiming no error returned. So, I go to the command
> prompt and run the following:
>
> «C:Program FilesPostgreSQL8.1binpg_ctl.exe» runservice
> -N «pgsql-8.1» -D «C:Program FilesPostgreSQL8.1data»
> pg_ctl: could not start service «psql-8.1»: error code 1063
>
> I tried googling that error code, but come up with nothing.
> Can someone tell us what this code means?

C:> net helpmsg 1063

The service process could not connect to the service controller.

You can’t use «runservice» from the commandline, only from the service
control manager. If you want to start it with pg_ctl, just use «pg_ctl
start».

Источник

Start service error 1063

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

‘m trying to start and stop the windows service programatically using a notify tray icon. The service and the System Tray Icon App can talk over Named pipes IPC. So, I took this example from msdn and added IPC schemes to it. This service on starting, installs himself (create service method) successfully. Now I don’t call him to start from services.msc.

Instead the Tray Icon pings the service and service pongs back. Then, the Tray ICon sends a start command. Upon receiving the start command, the service has to kick off him self and start running.

On Start Request from tray icon, I’m calling run service method in the example, which has the service table and service control dispatcher in it (I assume, the service control dispatcher will trigger a call onstart method from windows). But the service control dispatcher return the 1063 error. I tried with admin privileges and moving him to secure account etc., nothing worked.

Can someone help me where am I going wrong?

Источник

Solved: Suggestions To Fix Startservicectrldispatcher Failed With Error Code 1063

Table of Contents

PC running slow?

Over the past few weeks, some users have reported startservicectrldispatcher crashing with error code 1063. g.According to the list of system error codes, error 1063 is ERROR_FAILED_SERVICE_CONTROLLER_CONNECT. According to the documentation for StartServiceCtrlDispatcher, this skill error is returned when you try to launch this application as a console product (that is, double-click the executable or start debugging from within Visual Studio).

Visited 23k times

I see a strange error in a good Windows utility. My service calls StartServiceCtrlDispatcher () at the very beginning of main () , but sometimes also calls 1063 (ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) .

I know this error only occurs if the user immediately launches the program. (like a console program). But this is currently not the case. I added a swap check to the parent process of some utility when this error occurs and tells services.exe that it is the parent process (I think it’s safe to assume that SCM started my program successfully).

Unfortunately this error does not repeat itself on my development machine and I cannot debug it myself, but the error reported in the logs recorded on user systems is:

  • Only a few% of more or less all users of this program face this problem.
  • Although the nightmare does happen, it doesn’t seem to repeat itself. Next time the service is successfully deployed.
  • In this case, the problem is StartServiceCtrlDispatcher () persists for a second and then returns due to an error.

PC running slow?

ASR Pro is the ultimate solution for your PC repair needs! Not only does it swiftly and safely diagnose and repair various Windows issues, but it also increases system performance, optimizes memory, improves security and fine tunes your PC for maximum reliability. So why wait? Get started today!

Has anyone seen similar errors? So technically, what was the reason for each of our mistakes?

34.6 thousand 2727 gold badges 157157 jewelry badges 313313 bronze badges

I wanted to know on May 26, 15, 16:30.

279 11 of your unwanted watch badges 22 silver badges 77 bronze badges

Not The Answer You’re Looking For? Browse Other Requests Marked With The Windows Icon Winapi Windows-services, Or Ask Your Own Question.

As you can already see fromsome lack of response and all of this in search engines such as Yahoo, the problem is infrequent. Believe me, your problem lies with your service, and this one, in particular, is in the code that runs from the very beginning of the process to StartServiceCtrlDispatcher () , and most likely this usually requires some form distortion of the system resources. most likely heap or HANDLE .

You may be sorry to hear this, but I am not leaving you with a magical answer to your concerns. Instead, I suggest troubleshooting.

Microsoft’s app is invaluable for detecting damage. I suggest you:

  1. Install it to develop your favorite computer.
  2. Add your service exe file.
  3. For the first time only, select Basics Heaps .
  4. Click Save. It doesn’t matter if you leave Verifier open. Your application will be open.
  5. Start the service multiple times.
  6. If the concept fails, it is debugged and the failure indicates your problem.
  7. If it fails, do not add Basics Handles . Basics Heaps , on the other hand, can be calledvans “false positives” – errors in the voucher code that do not cause much harm. Either way, since you’re usually on the hunt, you’d better fix whatever you find. I’m most worried about the double HANDLE exception or something similar. If you free the HANDLE service handler from corruption, it can definitely lead to a problem.
  8. If it still doesn’t crash, you can try other strategies in Basics * , but I’m not interested if that helps.
  9. At this point, you want to view the code between the main () and StartServiceCtrlDispatcher () functions of the program, as well as any global constructors you have. Check for obstructions, overflows and errors in HANDLE .
  10. The next step may be to install Application Verifier on the client computer. It doesn’t hurt too much, sometimes I get sick when I can’t find the guilt myself.

answered Jun 8 15 at 21:37

7.237 22 white gold badges 3,434 silver badges 4040 bronze badges

TIP. I used _wfopen / fwrite / fclose to log some messages. Somehow 183 got started and internally this error was assigned to 1063. I deleted the job and it started working fine, nothing for the location. Every little mistake can lead anyone to this. If you start with services and run the list, you will see a salary error (183 in my case).

Источник

StartServiceCtrlDispatcher не может получить доступ к ошибке 1063

Я пишу на c ++ сервисе, но у меня есть ошибка, и я не могу ее исправить.

основная функция моего сервиса

Где я отлаживаю свою программу с аргументами командной строки (service_path и action) на StartServiceCtrlDispatcher каждый раз, когда возвращается ошибка 1063. Visual Studio запускаю под Администратором. Где я пишу неправильный код, пожалуйста, помогите.

ОБНОВИТЬ

Решение

Вы можете только позвонить StartServiceCtrlDispatcher когда ваш процесс был запущен диспетчером управления службами, то есть когда он фактически работает как служба. При вызове из любого другого контекста вы получите ERROR_FAILED_SERVICE_CONTROLLER_CONNECT (1063).

Судя по виду вашего кода, вы должны только звонить StartServiceControlDispatcher если не был передан аргумент командной строки, например, что-то вроде

Есть также некоторые другие проблемы с вашей функцией main (), в частности:

Неправильная подпись; argv [] это char, а не TCHAR

Кастинг argv [0] в TCHAR

Цикл, который вызывает GetLastError без причины, 114 раз

Использование memcmp вместо strcmp

Я не смотрел на ServiceMain ().

Другие решения

это происходит, когда служба установлена ​​поверх Windows 8 или более поздней версии из 64 битов и вызывается методом StartServiceCtrlDispatcher который вызовет основную точку входа. Но метод StartServiceCtrlDispatcher работает с указателем 8 бит.

Итак, решение состоит в том, чтобы использовать функцию StartServiceCtrlDispatcherW который работает с указателями 16 бит, например:

До: он использует указатель на LPTSTR (8 бит), это тип данных, которые нужны SERVICE_TABLE_ENTRY а также StartServiceCtrlDispatcher:

После: он использует указатель на LPWSTR (16 бит), это тип данных, которые нужны SERVICE_TABLE_ENTRYW а также StartServiceCtrlDispatcherW:

Используйте широкую строку (16 бит на символ) и функции StartServiceCtrlDispatcherW и SERVICE_TABLE_ENTRYW Type вместо StartServiceCtrlDispatcher и SERVICE_TABLE_ENTRY.

Источник

Невозможно запустить PostgreSQL как службу Windows

У меня было это в моих службах Windows:

Он никогда не заканчивает выполнение. Но если бы я сделал это в оболочке dos:

Обратите внимание, что я изменил только «runservice» на «start», и все работает отлично.

Команда runservice может быть выполнена только менеджером службы

чтобы исправить мой локальный хост Windows 7 для запуска postgres в качестве службы, я использовал следующую команду для запуска данных

Затем проверил статус на наличие ошибок

если вы получите ошибку 1063, это более чем вероятные разрешения, я выполнил следующую команду

затем перезапустил запуск/статус, он показал все нормально, но все равно диспетчер служб не запускал службу

Итак, в Services->postgresql->options->logon я установил вход в систему как учетную запись локальной системы вместо пользователя postgres, и вуаля, это сработало.

это случилось со мной, потому что я установил свой каталог данных где-то, к чему у учетной записи пользователя postgres windows не было доступа.

У меня была эта проблема в Windows после сбоя системы. Выполнение первой команды показало неверные данные в C:Program FilesPostgreSQL9.1datapostmaster.pid . Удаление этого файла помогло. Ссылка.

Я столкнулся с той же проблемой после перемещения вручную файлов данных базы данных (каталог PG_DATA) без повторного создания всех необходимых разрешений.

Вот как я решил свою проблему:

1. Проверьте права доступа к старому каталогу PG_DATA:

2. Проверьте права доступа к новому каталогу PG_DATA:

3. Сравните результаты 1 и 2.

Найдите различия между пользователями и/или разрешениями, а затем синхронизируйте их.

Примечание. Мне было проще использовать его explorer для этапа синхронизации, чем использовать его cacls непосредственно из командной строки.

Если вы изменили pg_hba.conf , возможно, вы что-то пропустили в файле. Например, после IP в этом файле должен быть CIDR. Должно быть как 192.168.1.100/32

Если вы забыли поставить 32, то сервер не перезагружается.

Подсказкой может быть изучение журналов запуска. В случае проблемы в pg_hba.conf вы можете увидеть что-то вроде этого:

Вам нужно проверить свои файлы журналов и журнал событий Windows, чтобы понять, в чем проблема. Если там вообще ничего нет, нужно выламывать что-то вроде Process Monitor и получать stacktrace того, где он завис.

У меня была эта проблема в прошлом, и она заключалась в том, что установщик неправильно настроил разрешения для пользователя, от имени которого должна была работать служба.

Я также столкнулся с этой проблемой с броском и ошибкой postgresql после попытки инициализировать кластер базы данных. После анализа файлов журнала и запуска сценариев командной строки в течение 4 часов у меня есть решение для всех, кто сталкивается с этой проблемой для версий Windows.

Это не подробное описание того, почему это происходит. Я устанавливал odoo 10, 11, 12 и 13 много раз на бесчисленное количество клиентских серверов и систем Windows, и это первый раз, когда я столкнулся с этой проблемой. Я не могу сказать, потому что у меня установлена ​​MS VS Enterprise и Android Studio на этой машине или что-то в этом роде. Но ниже приведен простой ответ о том, как это исправить, инициализировать кластер и создать файлы базы данных в папке данных.

Откройте папку данных для postgresql. — Для установки Odoo это обычно будет «C:Program Files (x86)Odoo 13.0PostgreSQL», если только вы не выбрали другое место при установке.

Удалите любые или все файлы из этой папки. В противном случае вы получите сообщение об ошибке при запуске initdb.exe.

Щелкните правой кнопкой мыши папку данных и откройте ее свойства. Перейдите на вкладку «Безопасность», а затем нажмите кнопку «Дополнительно» внизу.

Вам нужно изменить владельца этой папки на openpgsvc. Нажмите «Изменить», введите openpgsvc и нажмите «ОК». После этого установите флажок ниже, указав, что вы хотите, чтобы это изменение также повлияло на контейнеры с этим контейнером.

Затем на вкладке «Разрешения» нажмите кнопку «Добавить» внизу. Вам нужно добавить openpgsvc в качестве пользователя и дать этому пользователю полные права. Нажмите «Применить» и «ОК», чтобы закрыть все свойства папки.

Теперь вам нужно открыть cmd.exe. После открытия мы собираемся вызвать initdb.exe и также передать ему некоторые значения.

Сначала запустите chdir и измените рабочий каталог на расположение initdb.exe. Для меня при запуске odoo 13 на машине с Windows 10 это место.

«C:Program Files (x86)Odoo 13.0PostgreSQLbin»

  1. Есть одна переменная, которую нужно передать, чтобы это работало, вот список. ДОЛЖЕН БЫТЬ ВКЛЮЧЕН В ВЫЗОВ initdb.exe

Каталог данных Postgres: «C:Program Files (x86)Odoo 13.0PostgreSQLdata»

Конечный результат с параметром для моей установки будет выглядеть так:

Источник

StartServiceCtrlDispatcher error 1063

i created a service.
installed it
i get an error 1063 when trying to start the service using StartServiceCtrlDispatcher ();

what have i done wrong?

see the my code below.

// MyServiceTest.cpp : Defines the entry point for the console application.
//

#include «Windows.h»
#include «Winsvc.h»
#include «time.h»

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

SERVICE_STATUS m_ServiceStatus;
SERVICE_STATUS_HANDLE m_ServiceStatusHandle;

void WINAPI ServiceMain(DWORD argc, LPTSTR *argv);
void WINAPI ServiceCtrlHandler(DWORD Opcode);

BOOL InstallService();
BOOL DeleteService();

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
<
int nRetCode = 0;

// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHa ndle(NULL) , NULL, ::GetCommandLine(), 0))
<
//cerr 1)
<
if(strcmp(argv[1],»-i»)==0 )
<
if(InstallService())
printf(«nnService Installed Sucessfullyn»);
else
printf(«nnError Installing Servicen»);
>
else if(strcmp(argv[1],»-r»)==0 )
<
if(DeleteService())
printf(«nnService UnInstalled Sucessfullyn»);
else
printf(«nnError UnInstalling Servicen»);
>
else if(strcmp(argv[1],»-s»)==0 )
<
SERVICE_TABLE_ENTRY DispatchTable[]=
<<«MyServiceTestService»,S erviceMain >,>;

BOOL ret;
ret=StartServiceCtrlDispat cher(Dispa tchTable);
if (!ret)
<
char wcError[100];
sprintf(wcError, «StartServiceCtrlDispatche r Failed. Error Code %dn»,GetLastError());
TRACE(wcError);

//here i get error 1063

>
>
else
<
printf(«nnUnknown Usagenn»
«For Install use MyServiceTest -inn»
«For UnInstall use MyServiceTest -dn»);
>
>
else
<
printf(«nnUnknown Usagenn»
«For Install use MyServiceTest -inn»
«For UnInstall use MyServiceTest -dn»);
>
return 0;
>

void WINAPI ServiceMain(DWORD argc, LPTSTR *argv)
<
DWORD status;
DWORD specificError;
m_ServiceStatus.dwServiceT ype = SERVICE_WIN32;
m_ServiceStatus.dwCurrentS tate = SERVICE_START_PENDING;
m_ServiceStatus.dwControls Accepted = SERVICE_ACCEPT_STOP;
m_ServiceStatus.dwWin32Exi tCode = 0;
m_ServiceStatus.dwServiceS pecificExi tCode = 0;
m_ServiceStatus.dwCheckPoi nt = 0;
m_ServiceStatus.dwWaitHint = 0;

m_ServiceStatusHandle = RegisterServiceCtrlHandler («MyServic eTestServi ce»,
ServiceCtrlHandler);
if (m_ServiceStatusHandle == (SERVICE_STATUS_HANDLE)0)
<
return;
>
m_ServiceStatus.dwCurrentS tate = SERVICE_RUNNING;
m_ServiceStatus.dwCheckPoi nt = 0;
m_ServiceStatus.dwWaitHint = 0;
if (!SetServiceStatus (m_ServiceStatusHandle, &m_ServiceStatus))
<
>

bRunning=true;
while(bRunning)
<
AfxMessageBox(«Wait 3 seconds. «);
Sleep(3000);

void WINAPI ServiceCtrlHandler(DWORD Opcode)
<
switch(Opcode)
<
case SERVICE_CONTROL_PAUSE:
m_ServiceStatus.dwCurrentS tate = SERVICE_PAUSED;
break;
case SERVICE_CONTROL_CONTINUE:
m_ServiceStatus.dwCurrentS tate = SERVICE_RUNNING;
break;
case SERVICE_CONTROL_STOP:
m_ServiceStatus.dwWin32Exi tCode = 0;
m_ServiceStatus.dwCurrentS tate = SERVICE_STOPPED;
m_ServiceStatus.dwCheckPoi nt = 0;
m_ServiceStatus.dwWaitHint = 0;

SetServiceStatus (m_ServiceStatusHandle,&m_ ServiceSta tus);
bRunning=false;
break;
case SERVICE_CONTROL_INTERROGAT E:
break;
>
return;
>

BOOL InstallService()
<
char strDir[1024];
SC_HANDLE schSCManager,schService;
GetCurrentDirectory(1024,s trDir);
strcat(strDir,»\Debug\My ServiceTes t.exe»);
schSCManager = OpenSCManager(NULL,NULL,SC _MANAGER_A LL_ACCESS) ;

if (schSCManager == NULL)
return false;
LPCTSTR lpszBinaryPathName=strDir;

schService = CreateService(schSCManager ,»MyServic eTestServi ce»,
«SAM Job Importer», // service name to display
SERVICE_ALL_ACCESS, // desired access
SERVICE_WIN32_OWN_PROCESS, // service type
SERVICE_DEMAND_START, // start type
SERVICE_ERROR_NORMAL, // error control type
lpszBinaryPathName, // service’s binary
NULL, // no load ordering group
NULL, // no tag identifier
NULL, // no dependencies
NULL, // LocalSystem account
NULL); // no password

if (schService == NULL)
return false;

CloseServiceHandle(schServ ice);
return true;
>

BOOL DeleteService()
<
SC_HANDLE schSCManager;
SC_HANDLE hService;
schSCManager = OpenSCManager(NULL,NULL,SC _MANAGER_A LL_ACCESS) ;

if (schSCManager == NULL)
return false;
hService=OpenService(schSC Manager,»M yServiceTe stService» ,SERVICE_A LL_ACCESS) ;
if (hService == NULL)
return false;
if(DeleteService(hService) ==0)
return false;
if(CloseServiceHandle(hSer vice)==0)
return false;

Источник

Пытаюсь разработать свою первую службу Windows, и я отлаживаю в Windows 7 MS VC ++ 10.0. Как только он вызывает StartServiceCtrlDispatcher (), я получаю сообщение об ошибке 1063, и он говорит, что доступ запрещен. Я администратор, как именно мне пройти это? Я новичок в сфере услуг. Благодарю. Код:

// For WinXp, don't forget to link to
// Advapi32.lib library if needed...

#define _WIN32_WINNT 0x0501

#include <windows.h>

#include <stdio.h>
#include <tchar.h>

// Prototypes, just empty skeletons...

void SvcDebugOut(LPSTR String, DWORD Status);
void  WINAPI MyServiceCtrlHandler(DWORD opcode);
void  MyServiceStart(DWORD argc, LPTSTR *argv);
DWORD MyServiceInitialization(DWORD argc, LPTSTR *argv, DWORD *specificError);

void main()
{

// Using 2-D array as a table...

// The name of a service to be run in this service process - "MyService",

// The function as the starting point for a service - MyServiceStart or

// a pointer to a ServiceMain() function...

// The members of the last entry in the table must have NULL values

// to designate the end of the table...

SERVICE_TABLE_ENTRY  DispatchTable[] = {{_TEXT("MyService"), (LPSERVICE_MAIN_FUNCTION)MyServiceStart}, {NULL, NULL}};
if (!StartServiceCtrlDispatcher(DispatchTable))
SvcDebugOut("StartServiceCtrlDispatcher() failed, error: %dn", GetLastError());
else
printf("StartServiceCtrlDispatcher() looks OK.n");
return;
}

// ==========================================================================
// Prototype definitions...just skeletons here...
void  WINAPI MyServiceCtrlHandler(DWORD opcode)
{
// Service control information here...
return;
}

void  MyServiceStart(DWORD argc, LPTSTR *argv)
{
// Starting service information here...
return;
}DWORD MyServiceInitialization(DWORD argc, LPTSTR *argv, DWORD *specificError)
{
// Service initialization information here...
return 0;
}

// Very simple info to the standard output...
void SvcDebugOut(LPSTR String, DWORD Status)
{
CHAR  Buffer[1024];
printf("In SvcDebugOut() lol!n");
if (strlen(String) < 1000)
{
sprintf(Buffer, String, Status);
OutputDebugStringA(Buffer);
}
else
printf("String too long...n");
return;
}

3

Решение

это сообщение отвечает правильно. Пока вы не запустите сервис «как сервис», он не будет работать.

Вы должны зарегистрировать это. Для этого посмотрите на это файл, это реализация сервиса Apple Bonjour с открытым исходным кодом.

Это дает хорошее представление о том, что необходимо сделать для установки службы. Особенно метод InstallService — и RemoveService (если вы хотите его удалить).

1

Другие решения

Сервисы запускаются под учетной записью, указанной в свойствах их регистрации. Это может не совпадать с учетной записью, которая регистрирует службу или запускает ее. Читает об этом.

Многие сервисы работают под учетной записью «Сетевой сервис», которая имеет очень ограниченные возможности. Это имеет смысл, поскольку многие службы обрабатывают запросы, поступающие из сети. Вот почему «Сетевой сервис» был выбран Microsoft по умолчанию.

0

Содержание

  1. Невозможно запустить PostgreSQL как службу Windows
  2. 11 ответы
  3. 1. Проверьте права доступа к старому каталогу PG_DATA:
  4. 2. Проверьте права доступа к новому каталогу PG_DATA:
  5. 3. Сравните выходы из 1. и 2.
  6. Re: Error code 1063
  7. Почему может не запускаться служба Postgres?
  8. pg_ctl: could not start service «pgsql-8.2»: error code 1063
  9. Responses
  10. Browse pgsql-general by date
  11. Re: pg_ctl: could not start service «pgsql-8.2»: error code 1063

Невозможно запустить PostgreSQL как службу Windows

У меня было это в моих службах Windows:

Он никогда не прекращает выполнение. Но если бы я сделал это в оболочке dos:

Обратите внимание, что я только изменил «runservice» на «start», и он работает нормально.

11 ответы

Команду runservice может выполнять только диспетчер служб.

чтобы исправить мой localhost windows 7 для запуска postgres как службы, я использовал следующую команду для запуска данных

Потом проверил статус на наличие ошибок

если вы получите ошибку 1063, это более чем вероятные разрешения, я выполнил следующую команду

затем повторно запустите запуск / статус, он показал все нормально, но диспетчер служб не запускал службу

Итак, в Services-> postgresql-> options-> logon я установил вход как локальную системную учетную запись вместо пользователя postgres, и вуаля, это сработало.

Создан 13 июля ’12, 17:07

У меня это тоже сработало. postgresql 9.5.2. Вкратце: в сервисах выберите сервис и просмотрите его свойства и измените логин на локальную систему — Александр Риос

Вместо postgres пользователь, я использовал NETWORK_SERVICE Пользователь. Подробнее см. Здесь: stackoverflow.com/a/38563535/363573 — Stephan

это случилось со мной, потому что я установил каталог данных где-то там, где учетная запись пользователя postgres Windows не имела доступа.

Это ИМЕННО причина, по которой это происходит! Вы должны изменить каталог данных во время установки, чтобы избежать этой проблемы — Анонимный

Для случайного читателя вот простой способ правильно установить права доступа к каталогу данных: stackoverflow.com/a/38563535/363573. — Stephan

Следует отметить, что по умолчанию PostgreSQL в Windows, похоже, использует NetworkService в качестве пользователя. — Барт Фридрихс

Я столкнулся с той же проблемой после перемещение вручную файлов данных базы данных (Каталог PG_DATA) без воссоздания всех необходимых разрешений.

Вот как я решил свою проблему:

1. Проверьте права доступа к старому каталогу PG_DATA:

2. Проверьте права доступа к новому каталогу PG_DATA:

3. Сравните выходы из 1. и 2.

Найдите различия между пользователями и / или разрешениями, а затем синхронизируйте их.

Примечание: Мне было проще использовать explorer для шага синхронизации, а не использовать cacls прямо из командной строки.

Создан 25 июля ’16, 10:07

У меня была эта проблема в Windows после сбоя системы. Выполнение первой команды показало неверные данные в C:Program FilesPostgreSQL9.1datapostmaster.pid . Удаление этого файла помогло. Ссылка.

ответ дан 06 дек ’13, 19:12

Если вы изменили pg_hba.conf , возможно, вы что-то пропустили в файле. Например, в этом файле после IP должен быть CIDR. Должно быть 192.168.1.100/32

Если вы забыли поставить 32, то сервер не перезагружается.

Ключом к разгадке может быть исследование журналов запуска. Дело в том, что проблема в pg_hba.conf можно было увидеть что-то вроде этого:

Вам нужно проверить свои файлы журналов и журнал событий Windows, чтобы понять, в чем проблема. Если там вообще ничего нет, вам нужно вырвать что-то вроде Process Monitor и получить трассировку стека, где он завис.

ответ дан 09 авг.

У меня была эта проблема в прошлом, и дело было в том, что установщик неправильно настроил разрешения для пользователя, от имени которого должна была запускаться служба.

ответ дан 27 авг.

Я также столкнулся с этой проблемой с выбросом postgresql и ошибкой после попытки инициализировать кластер базы данных. После анализа файлов журнала и запуска сценариев командной строки в течение 4 часов у меня есть решение для всех, кто сталкивается с этой проблемой для версий Windows.

Это не подробное описание того, почему это происходит. Я устанавливал odoo 10, 11, 12 и 13 много раз на бесчисленное количество клиентских серверов и систем Windows, и это первый раз, когда я столкнулся с этой проблемой. Я не могу сказать, потому что у меня установлен MS VS Enterprise и Android Studio на этом компьютере или что-то в этом роде. Но ниже приводится простой ответ о том, как это исправить, инициализировать кластер и создать файлы базы данных в папке данных.

Откройте папку данных для postgresql. — Для установки Odoo это обычно будет «C: Program Files (x86) Odoo 13.0 PostgreSQL», если вы не выбрали другое место при установке.

Удалите все или все файлы из этой папки — в противном случае вы получите сообщение об ошибке при запуске initdb.exe.

Щелкните правой кнопкой мыши папку с данными и откройте для нее свойства. Щелкните вкладку «Безопасность», а затем нажмите кнопку «Дополнительно» внизу.

Вам необходимо изменить владельца этой папки на openpgsvc. Нажмите «Изменить», введите openpgsvc и нажмите «ОК». После этого установите флажок ниже, говоря, что вы хотите, чтобы это изменение также повлияло на контейнеры с этим контейнером.

Затем на вкладке «Разрешения» нажмите кнопку «Добавить» внизу. Вам необходимо добавить openpgsvc в качестве пользователя и предоставить этому пользователю полные права. Нажмите «Применить» и «ОК», чтобы закрыть все свойства папки.

Теперь вам нужно открыть cmd.exe — после открытия мы вызовем initdb.exe и также передадим ему некоторые значения.

Сначала запустите chdir и измените рабочий каталог на место initdb.exe. Для меня, когда я запускаю odoo 13 на машине с Windows 10, это расположение ..

«C: Program Files (x86) Odoo 13.0 PostgreSQL bin»

  1. Есть еще одна переменная, которую также необходимо передать, чтобы эта работа работала, — это список. НЕОБХОДИМО ВКЛЮЧИТЬ В ЗВОНОК initdb.exe

Каталог данных Postgres: «C: Program Files (x86) Odoo 13.0 PostgreSQL data»

Конечный результат с параметром для моей установки будет выглядеть так:

Источник

Re: Error code 1063

From: «Magnus Hagander»
To: «Robert Fitzpatrick»
, «PostgreSQL»

Subject: Re: Error code 1063 Date: 2006-07-12 12:13:51 Message-ID: 6BCB9D8A16AC4241919521715F4D8BCEA0FAEC@algol.sollentuna.se Views: Raw Message | Whole Thread | Download mbox | Resend email Thread: Lists: pgsql-general

> We have PostgreSQL 8.1 running on Windows 2000 for a few
> weeks now, when we try to start the service, it could not
> start claiming no error returned. So, I go to the command
> prompt and run the following:
>
> «C:Program FilesPostgreSQL8.1binpg_ctl.exe» runservice
> -N «pgsql-8.1» -D «C:Program FilesPostgreSQL8.1data»
> pg_ctl: could not start service «psql-8.1»: error code 1063
>
> I tried googling that error code, but come up with nothing.
> Can someone tell us what this code means?

C:> net helpmsg 1063

The service process could not connect to the service controller.

You can’t use «runservice» from the commandline, only from the service
control manager. If you want to start it with pg_ctl, just use «pg_ctl
start».

Источник

Почему может не запускаться служба Postgres?

Всех приветствую, подскажите, скачал и установил PostgreSQL 12.1.3 для Windows, для изучения, система у меня — Windows 7×64 со всеми обновами, уже на этапе установки выскакивает ошибка что невозможно законнектится к службе постргреса,




если продолжить то потом при входе в админскую панель в браузере с помощью pgAdmin4 невозможно создать сервер — коннект к службе так же невозможен
Если открыть панель служб винды то там служба postgresql-x64-12 висит со статусом остановлена — запустить её вручную неудается — выходит сообщение — служба была запущена и сразу установлена, пробовал скопировать строчку запуска службы —
«C:PostgreSQL12binpg_ctl.exe» runservice -N «postgresql-x64-12» -D «C:PostgreSQL12data» -w
И вставил её в командную строку — ни в обычной ни в админской коммандн.строке не запускается:
C:>»C:PostgreSQL12binpg_ctl.exe» runservice -N «postgresql-x64-12» -D «C:PostgreSQL12data» -w
pg_ctl: не удалось запустить службу «postgresql-x64-12» (код ошибки: 1063)

Пробовал гуглить — проблема ненова но в основном она у всех после длительного использования — кэш почистили настройки некоторые сбросили — и все запустилось, а у меня нечего чистить и сбрасывать — чистая новая установка, странно, что делать?

Источник

pg_ctl: could not start service «pgsql-8.2»: error code 1063

From: Stefano T
To: pgsql-general(at)postgresql(dot)org
Subject: pg_ctl: could not start service «pgsql-8.2»: error code 1063
Date: 2007-05-05 16:45:10
Message-ID: 1178383510.463603.250330@h2g2000hsg.googlegroups.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi everybody.
Well.. i’ve a probelm. pg doesn’t start at boot. if i copy the string
of command and try execute:

C:ProgramsPostgreSQL8.2binpg_ctl.exe runservice -N «pgsql-8.2» -D
«C:ProgramsPostgreSQL8.2data»
the output is:
pg_ctl: could not start service «pgsql-8.2»: error code 1063

and if i try to execute this:
C:WINDOWSsystem32net.exe start pgsql-8.2

The PostgreSQL Database Server 8.2 service is starting.
The PostgreSQL Database Server 8.2 service could not be started.
The service did not report an error.

and the execution of this:
C:ProgramsPostgreSQL8.2bin>psql.exe
psql: could not connect to server: Connection refused (0x0000274D/
10061)
Is the server running on host «. » and accepting
TCP/IP connections on port 5432?

some one can help me? how can i fix this problem?

Responses

  • Re: pg_ctl: could not start service «pgsql-8.2»: error code 1063 at 2007-05-07 17:14:50 from Magnus Hagander

Browse pgsql-general by date

From Date Subject
Next Message Michael Nolan 2007-05-05 21:50:49 Refreshing a warm spare with WAL files
Previous Message Sebastian Hennebrueder 2007-05-05 15:54:33 Re: Feature Request — was: PostgreSQL Performance Tuning

Copyright © 1996-2022 The PostgreSQL Global Development Group

Источник

Re: pg_ctl: could not start service «pgsql-8.2»: error code 1063

From: Magnus Hagander
To: Stefano T
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: pg_ctl: could not start service «pgsql-8.2»: error code 1063
Date: 2007-05-07 17:14:50
Message-ID: 463F5E8A.4090306@hagander.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Stefano T wrote:
> Hi everybody.
> Well.. i’ve a probelm. pg doesn’t start at boot. if i copy the string
> of command and try execute:
>
> C:ProgramsPostgreSQL8.2binpg_ctl.exe runservice -N «pgsql-8.2» -D
> «C:ProgramsPostgreSQL8.2data»
> the output is:
> pg_ctl: could not start service «pgsql-8.2»: error code 1063

runservice can only be used fromthe service control manager, as the
error indicates.

> and if i try to execute this:
> C:WINDOWSsystem32net.exe start pgsql-8.2
>
> the output is:
>
> The PostgreSQL Database Server 8.2 service is starting.
> The PostgreSQL Database Server 8.2 service could not be started.
> The service did not report an error.

What do you get in the eventlog and/or the postgresql log at this time?

Источник

Чем вызывывается и что означает ошибка 1063 (The service process could not connect to the service controller) при запуске сервиса? Как с этим бороться?

Здравствуйте, <Аноним>, Вы писали:

А>Чем вызывывается и что означает ошибка 1063 (The service process could not connect to the service controller) при запуске сервиса? Как с этим бороться?

А на код основных функций сервиса можно взглянуть? Точка входа, ServiceMain(), Handler()…

[ posted via RSDN@Home 1.1.2 stable, accompanied by Iron Maiden — The Loneliness Of The Long Distance Runner ]

— Искренне ваш, Поросенок Пафнутий ~ ICQ#116846877 http://web.icq.com/whitepages/online?icq=116846877&img=21
In Windows, there’s always a catch… © Paul DiLascia

Здравствуйте, SchweinDeBurg, Вы писали:

SDB>А на код основных функций сервиса можно взглянуть? Точка входа, ServiceMain(), Handler()…


SERVICE_STATUS_HANDLE  StatusHandle;

void WINAPI ServiceMain (DWORD dwArgc, LPTSTR *lpszArgv)
{
   // Сюда мы уже не попадаем :-/
}

void main(int argc, char **argv)
{
    if (argc > 1)
    {
        if (_stricmp("/install", argv[1] + 1) == 0)
        {
            Install();
        }
        else
        if (_stricmp("/remove", argv[1] + 1) == 0)
        {
            Remove();
        }
        else
        {
            printf ("Usage: n"
                    " " SERVICE_NAME " /install        - install servicen"
                    " " SERVICE_NAME " /remove         - remove servicen"
            );
        }
    }
    else
    {
        SERVICE_TABLE_ENTRY dispatchTable[] =
        {
            { SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION) ServiceMain },
            { NULL, NULL }
        };    

        if (!StartServiceCtrlDispatcher(dispatchTable))
        {
            printf ("StartServiceCtrlDispatcher failed, err.0x%xn", GetLastError());
        }
    }

Запуск из командной строки без аргументов, ServiceMain() не вызывается.

Здравствуйте, Аноним, Вы писали:

А>Здравствуйте, SchweinDeBurg, Вы писали:


SDB>>А на код основных функций сервиса можно взглянуть? Точка входа, ServiceMain(), Handler()…

Все, вопрос снят. Туплю блин.
Думаю что когда сервис стартует из командной строки, CSM-менеджер не открыт, поэтому StartServiceCtrlDispatcher() возвращает ошибку.

Понравилась статья? Поделить с друзьями:
  • Windows service could not start the service on local computer error 1053
  • Windows update client failed to detect with error 0x80240440
  • Windows server 2019 как изменить часовой пояс
  • Windows update client failed to detect with error 0x80240438
  • Windows server 2019 acpi bios error