Startservicectrldispatcher failed error code 1063

Функция StartServiceCtrlDispatcher Функция StartServiceCtrlDispatcher устанавливает связь главного потока процесса службы с диспетчером управления службами, который заставляет поток быть потоком диспетчера управления службой для вызывающего процесса. Параметры [in] Указатель на массив структур SERVICE_TABLE_ENTRY, имеющих в своем составе одну запись для каждой службы, которая может выполнить код в вызывающем процесс. Члены структуры последней записи в таблице […]

Содержание

  1. Функция StartServiceCtrlDispatcher
  2. Параметры
  3. Возвращаемые значения
  4. StartServiceCtrlDispatcherW function (winsvc.h)
  5. Syntax
  6. Parameters
  7. Return value
  8. Remarks
  9. Examples
  10. StartServiceCtrlDispatcherA function (winsvc.h)
  11. Syntax
  12. Parameters
  13. Return value
  14. Remarks
  15. Examples
  16. Solved: Suggestions To Fix Startservicectrldispatcher Failed With Error Code 1063
  17. PC running slow?
  18. PC running slow?
  19. Not The Answer You’re Looking For? Browse Other Requests Marked With The Windows Icon Winapi Windows-services, Or Ask Your Own Question.

Функция StartServiceCtrlDispatcher

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

Параметры

[in] Указатель на массив структур SERVICE_TABLE_ENTRY, имеющих в своем составе одну запись для каждой службы, которая может выполнить код в вызывающем процесс. Члены структуры последней записи в таблице должны иметь значения значения ПУСТО (NULL), чтобы определять конец таблицы.

Возвращаемые значения

Если функция завершается успешно, возвращаемое значение является ненулевым.

Если функция завершается ошибкой, возвращаемое значение — нуль. Чтобы получить дополнительную информацию об ошибке, вызовите GetLastError.

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

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

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

ERROR_INVALID_DATA Указанная координирующая таблица имеет в своем составе записи, которые находятся в неправильном формате. ERROR_SERVICE_ALREADY_RUNNING Процесс уже вызвал StartServiceCtrlDispatcher. Каждый процесс может вызвать StartServiceCtrlDispatcher только один раз.

Windows NT: Это значение не поддерживается.

Когда диспетчер управления службами запускает процесс службы, он ставит его в режим ожидания, чтобы вызвать функцию StartServiceCtrlDispatcher. Главный поток процесса службы должен сделать этот вызов как можно скорее после того, как он запуститься. Если вызов функции StartServiceCtrlDispatcher завершается успешно, она устанавливает связь вызывающего потока с диспетчером управления службами и не возвращает значение до тех пор, пока все запущенные службы в процессе не завершаться. Диспетчер управления службами использует эту связь, чтобы отправлять управление и запускать службы по запросу главного потока процесса службы. Главный поток действует как диспетчер, вызывая соответствующую функцию HandlerEx, чтобы обработать запросы на управление, или создавая новый поток, чтобы выполнить соответствующую функцию ServiceMain, когда новая служба запускается.

Параметр lpServiceTable имеет в своем составе запись для каждой службы, которая может запуститься в вызывающем процесс. Каждая запись задает функцию ServiceMain для этой службы. Для служб SERVICE_WIN32_SHARE_PROCESS , каждая запись должна иметь в своем составе имя службы. Это имя — имя службы, которое определялось функцией CreateService, когда служба была установлена. Для служб SERVICE_WIN32_OWN_PROCESS игнорируется имя службы в записи таблицы.

Если служба запускается в своем собственном процессе, главный поток процесса службы должен немедленно вызвать StartServiceCtrlDispatcher. Все задачи инициализации делаются в функции ServiceMain службы, когда служба запускается.

Если несколько служб совместно используют процесс и нужна какая-то общая инициализация всего процесса, то нужно прежде всего вызывать любую функцию ServiceMain, главный поток которой может сделать эту работу перед вызовом StartServiceCtrlDispatcher, занимая для нее меньше чем 30 секунд. Иначе, должен создаться другой поток, чтобы сделать инициализацию всего процесса, в то время как главный поток вызывает StartServiceCtrlDispatcher, и стать диспетчером управления службой. Любая специальная для службы инициализация должна все же делаться в отдельных главных функциях служб.

Размещение и совместимость StartServiceCtrlDispatcher

Источник

StartServiceCtrlDispatcherW function (winsvc.h)

Connects the main thread of a service process to the service control manager, which causes the thread to be the service control dispatcher thread for the calling process.

Syntax

Parameters

A pointer to an array of SERVICE_TABLE_ENTRY structures containing one entry for each service that can execute in the calling process. The members of the last entry in the table must have NULL values to designate the end of the table.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

The following error code can be set by the service control manager. Other error codes can be set by the registry functions that are called by the service control manager.

Return code Description
ERROR_FAILED_SERVICE_CONTROLLER_CONNECT This error is returned if the program is being run as a console application rather than as a service.

If the program will be run as a console application for debugging purposes, structure it such that service-specific code is not called when this error is returned.

ERROR_INVALID_DATA The specified dispatch table contains entries that are not in the proper format.
ERROR_SERVICE_ALREADY_RUNNING The process has already called StartServiceCtrlDispatcher. Each process can call StartServiceCtrlDispatcher only one time.

When the service control manager starts a service process, it waits for the process to call the StartServiceCtrlDispatcher function. The main thread of a service process should make this call as soon as possible after it starts up (within 30 seconds). If StartServiceCtrlDispatcher succeeds, it connects the calling thread to the service control manager and does not return until all running services in the process have entered the SERVICE_STOPPED state. The service control manager uses this connection to send control and service start requests to the main thread of the service process. The main thread acts as a dispatcher by invoking the appropriate HandlerEx function to handle control requests, or by creating a new thread to execute the appropriate ServiceMain function when a new service is started.

The lpServiceTable parameter contains an entry for each service that can run in the calling process. Each entry specifies the ServiceMain function for that service. For SERVICE_WIN32_SHARE_PROCESS services, each entry must contain the name of a service. This name is the service name that was specified by the CreateService function when the service was installed. For SERVICE_WIN32_OWN_PROCESS services, the service name in the table entry is ignored.

If a service runs in its own process, the main thread of the service process should immediately call StartServiceCtrlDispatcher. All initialization tasks are done in the service’s ServiceMain function when the service is started.

If multiple services share a process and some common process-wide initialization needs to be done before any ServiceMain function is called, the main thread can do the work before calling StartServiceCtrlDispatcher, as long as it takes less than 30 seconds. Otherwise, another thread must be created to do the process-wide initialization, while the main thread calls StartServiceCtrlDispatcher and becomes the service control dispatcher. Any service-specific initialization should still be done in the individual service main functions.

Services should not attempt to display a user interface directly. For more information, see Interactive Services.

Examples

The winsvc.h header defines StartServiceCtrlDispatcher as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.

Источник

StartServiceCtrlDispatcherA function (winsvc.h)

Connects the main thread of a service process to the service control manager, which causes the thread to be the service control dispatcher thread for the calling process.

Syntax

Parameters

A pointer to an array of SERVICE_TABLE_ENTRY structures containing one entry for each service that can execute in the calling process. The members of the last entry in the table must have NULL values to designate the end of the table.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

The following error code can be set by the service control manager. Other error codes can be set by the registry functions that are called by the service control manager.

Return code Description
ERROR_FAILED_SERVICE_CONTROLLER_CONNECT This error is returned if the program is being run as a console application rather than as a service.

If the program will be run as a console application for debugging purposes, structure it such that service-specific code is not called when this error is returned.

ERROR_INVALID_DATA The specified dispatch table contains entries that are not in the proper format.
ERROR_SERVICE_ALREADY_RUNNING The process has already called StartServiceCtrlDispatcher. Each process can call StartServiceCtrlDispatcher only one time.

When the service control manager starts a service process, it waits for the process to call the StartServiceCtrlDispatcher function. The main thread of a service process should make this call as soon as possible after it starts up (within 30 seconds). If StartServiceCtrlDispatcher succeeds, it connects the calling thread to the service control manager and does not return until all running services in the process have entered the SERVICE_STOPPED state. The service control manager uses this connection to send control and service start requests to the main thread of the service process. The main thread acts as a dispatcher by invoking the appropriate HandlerEx function to handle control requests, or by creating a new thread to execute the appropriate ServiceMain function when a new service is started.

The lpServiceTable parameter contains an entry for each service that can run in the calling process. Each entry specifies the ServiceMain function for that service. For SERVICE_WIN32_SHARE_PROCESS services, each entry must contain the name of a service. This name is the service name that was specified by the CreateService function when the service was installed. For SERVICE_WIN32_OWN_PROCESS services, the service name in the table entry is ignored.

If a service runs in its own process, the main thread of the service process should immediately call StartServiceCtrlDispatcher. All initialization tasks are done in the service’s ServiceMain function when the service is started.

If multiple services share a process and some common process-wide initialization needs to be done before any ServiceMain function is called, the main thread can do the work before calling StartServiceCtrlDispatcher, as long as it takes less than 30 seconds. Otherwise, another thread must be created to do the process-wide initialization, while the main thread calls StartServiceCtrlDispatcher and becomes the service control dispatcher. Any service-specific initialization should still be done in the individual service main functions.

Services should not attempt to display a user interface directly. For more information, see Interactive Services.

Examples

The winsvc.h header defines StartServiceCtrlDispatcher as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.

Источник

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).

Источник

  • Remove From My Forums
  • Question

  • Hello,

    my Name is Harry Diel and I’m a Software-Engineer (Development) here in Germany.


    A couple of years ago (2000-2005) I developed for a Medical-Assosiation under Windows XP and Server 2003 with MFC und Visual C 6.0 a LAN-Manager System with some RPC-programs, which where
    running as services on several clients, in a large System-LAN environment with more than 1500 installed workstations (NT/XP), Printern and over 200 Servers with Windows 2003 / NT. everything was OK, until now the first Windows Vista will be used.

    The Time has come to upgrade to Windows Vista !!!!

    Now I updated my C-Programs to Visual C++ 9.0 and VS 2008. The functionalities of the program were still the same, nothing changed. But now I get from the StartServiceCtrlDispatcher Function always the Error-Code “1063” =

    ERROR_FAILED_SERVICE_CONTROLLER_CONNECT. (Only when the service starts on Windows Vista).

    I need help, what can I do. I tried everything, but nothing works and helps realy.

    Enclosed you will find a piece of my Program-Code of the C++ program, when the service should start working. But it stops!!!!

    Maybe you can send me an example for Windows Vista how it would work.

    I am waiting for an answer. Thank you.

    regards

    harry Diel,

    47475 Kamp-Lintfort, Germany

    E-Mail: harry.diel@t-online.de

    1 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  
    2 int Win_RemComServiceMain (void)  
    3 {   ///////////////////////////////////////////////////////////////////////////////  
    4     sprintf (szOpenFName,»%s»,»C:\Temp\RemComLogDatei.log»);  
    5         hOpenF = CreateFile (szOpenFName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ,  
    6                     NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);         
    7  
    8     if (hOpenF == (HANDLE)ERROR)   
    9     {  hOpenF = NULL;  
    10     }  
    11     ///////////////////////////////////////////////////////////////////////////////  
    12     _GetDateAndTime();  
    13     sprintf(sWrkBuff,»%.6s | %stWin_RemComServiceMaint: LogFile gestartet.%s»,ActDatum, sCurrTime, EOR);  
    14      WriteErrorText_2 (sWrkBuff);  
    15     ///////////////////////////////////////////////////////////////////////////////  
    16     // Register the service control handler  
    17         g_hstatus = RegisterServiceCtrlHandler(REMC_SERVICENAME, ServiceCtrl);  
    18         if (g_hstatus == 0)  
    19          return FALSE;  
    20       
    21     // Setzen einiger Service-Standard Status-Values     
    22     g_ServiceMode = TRUE;  
    23     SetProcessShutdownParameters(0x100, 0);  
    24  
    25     // Erstelle einen Service Tabellen-Eintrag  
    26     SERVICE_TABLE_ENTRY dispatchTable[] =  
    27     {   {REMC_SERVICENAME, (LPSERVICE_MAIN_FUNCTION) RemComDoService},  
    28         {NULL, NULL}  
    29     };  
    30     ///////////////////////////////////////////////////////////////////////////////  
    31     _GetDateAndTime();  
    32     sprintf(sWrkBuff,»%.6s | %stStartServiceCtrlDispatchert%s%s»,ActDatum, sCurrTime, REMC_SERVICENAME, EOR);  
    33         WriteErrorText_2 (sWrkBuff);  
    34  
    35     // Aufrufen des Service-Control-Dispatcher mit unserem Tabellen-Eintrag  
    36     bRetc = StartServiceCtrlDispatcher(dispatchTable);  
    37     if (bRetc == TRUE)  
    38     {  return TRUE;  
    39     }  
    40     SvcError = GetLastError();  
    41     if (SvcError == ERROR_SERVICE_ALREADY_RUNNING)  
    42       return TRUE;  
    43     else  
    44     {  _GetDateAndTime();  
    45        sprintf(sWrkBuff,»%.6s | %stStartServiceCtrlDispatchertFehler = %d%s»,ActDatum, sCurrTime, SvcError, EOR);  
    46        WriteErrorText_2 (sWrkBuff);  
    47        return FALSE;  
    48     }  
    49 }  
    50  
    51 ///////////////////////////////////////////////////////////////////////////////////  
    52 // RemComService Main-Routines  
    53 ///////////////////////////////////////////////////////////////////////////////////  
    54 BOOL WINAPI RemComDoService (DWORD argc, char **argv)  
    55 {     
    56     // Setzen einiger Service-Standard Status-Values     
    57     g_srvstatus.dwServiceType = SERVICE_WIN32 | SERVICE_INTERACTIVE_PROCESS;  
    58         g_srvstatus.dwServiceSpecificExitCode = 0;  
    59     // Give this status to the SCM  
    60           
    61     if (!ReportStatus (SERVICE_START_PENDING, NO_ERROR, 15000))  
    62     {  ReportStatus (SERVICE_STOPPED, g_error, 0);  
    63        return FALSE;  
    64     }  
    65  
    66     hRemCThread = CreateThread (&SecAttributes, NULL,  
    67                         (LPTHREAD_START_ROUTINE) RemComServiceThread,  
    68                          NULL,  
    69                          NULL,   
    70                          &dwThreadId);  
    71     ///////////////////////////////////////////////////////////////////////////////  
    72     _GetDateAndTime();  
    73     sprintf(sWrkBuff,»%.6s | %stRemComDoServicetCreateThread OK.%s»,ActDatum, sCurrTime, EOR);  
    74         WriteErrorText_2 (sWrkBuff);  
    75         return TRUE;  
    76 }  
    77  
    78 ///////////////////////////////////////////////////////////////////////////////////  
    79 // Service Start-Routine — Thread that calls WinVNCAppMain  
    80 ///////////////////////////////////////////////////////////////////////////////////  
    81 BOOL RemComServiceThread (void *arg)  
    82 {  
    83     g_servicethread = GetCurrentThreadId();  
    84  
    85     bRetc = ReportStatus (SERVICE_RUNNING, NO_ERROR, 0);  
    86     if (bRetc != TRUE)    
    87       return FALSE;  
    88  
    89     ///////////////////////////////////////////////////////////////////////////////  
    90     _GetDateAndTime();  
    91     sprintf(sWrkBuff,»%.6s | %stRemComServiceThreadtgestartet: Service_Running —> Call DoModal()%s»,ActDatum, sCurrTime, EOR);  
    92         WriteErrorText_2 (sWrkBuff);  
    93  
    94     // The Service should start the Dialog !  
    95     AfxEnableControlContainer();  
    96     pRemCService->DoModal();  
    97  
    98     // Wir laufen nicht mehr ….  
    99     g_servicethread = NULL;  
    100  
    101     ReportStatus (SERVICE_STOPPED, g_error, 0);  
    102     return TRUE;  
    103 }  
    104  
    105 ///////////////////////////////////////////////////////////////////////////////  
    106 ///////////////////////////////////////////////////////////////////////////////  
    107  
    108  

    .

Чем вызывывается и что означает ошибка 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() возвращает ошибку.

Понравилась статья? Поделить с друзьями:
  • Startservice ошибка 1058
  • Startservice failed with error 4294967201
  • Startservice failed with error 193
  • Startservice error 577 unable to start service acsock
  • Startrep exe ошибка приложения память не может быть read windows 7