Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

How to start a service programmatically

Posted on 2006-04-27
11
Medium Priority
?
2,132 Views
Last Modified: 2013-12-03
I have a service app, which I'm able to install with no problem, but I can't figure out how to start it without having to go to the windows Service menu.

I had code to do this before, but my repository hard drive recently went bad, and I've lost all my example code.

How can I programmatically start a service application?
0
Comment
Question by:Axter
  • 7
  • 4
11 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 2000 total points
ID: 16552985
The idea is to

void    StartService        (   LPCTSTR             pszName,
                                int                 argc,
                                const wchar_t**     argv
                            )
{
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;

    schSCManager    =   OpenSCManager   (   NULL,                   // machine (NULL == local)
                                            NULL,                   // database (NULL == default)
                                            SC_MANAGER_ALL_ACCESS   // access required
                                        );
    if  (   schSCManager)
        {
            schService  =   OpenService (   schSCManager,
                                            pszName,
                                            SERVICE_ALL_ACCESS
                                        );

            if  (   schService)
                {
                    // try to start the service
                    if  (   StartService    (   schService,
                                                argc,
                                                argv
                                            )
                        )
                        {
                            wprintf (   TEXT    (   "Starting %s."),
                                        pszName
                                    );

                            Sleep   (   1000 );

                            while   (   QueryServiceStatus  (   schService,
                                                                &g_ssStatus
                                                            )
                                    )
                                    {
                                        if  (       SERVICE_START_PENDING  
                                                ==  g_ssStatus.dwCurrentState
                                            )
                                            {
                                                wprintf (   TEXT    (   "."));
                                                Sleep( 1000 );
                                            }
                                        else
                                                break;
                                    }

                            if  (   SERVICE_RUNNING ==  g_ssStatus.dwCurrentState)
                                    wprintf (   TEXT    (   "\n%s started.\n"),
                                                pszName
                                            );
                            else
                                    wprintf (   TEXT    (   "\n%s failed to start.\n"),
                                                pszName
                                            );

                        }

                CloseServiceHandle  (   schService);
            }
            else
                wprintf (   TEXT    (   "OpenService failed - %s\n"),
                            GetLastErrorText    (   g_szErr,    ERROR_BUFSZ)
                        );

            CloseServiceHandle  (   schSCManager);
        }
    else
            wprintf (   TEXT    (   "OpenSCManager failed - %s\n"),
                        GetLastErrorText    (   g_szErr,    ERROR_BUFSZ)
                    );
}



void    StopService    ( LPCTSTR pszName)
{
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;

    schSCManager    =   OpenSCManager   (   NULL,                   // machine (NULL == local)
                                            NULL,                   // database (NULL == default)
                                            SC_MANAGER_ALL_ACCESS   // access required
                                        );
    if  (   schSCManager)
        {
            schService  =   OpenService (   schSCManager,
                                            pszName,
                                            SERVICE_ALL_ACCESS
                                        );

            if  (   schService)
                {
                    // try to stop the service
                    if  (   ControlService  (   schService,
                                                SERVICE_CONTROL_STOP,
                                                &g_ssStatus
                                            )
                        )
                        {
                            wprintf (   TEXT    (   "Stopping %s."),
                                        pszName
                                    );

                            Sleep   (   1000 );

                            while   (   QueryServiceStatus  (   schService,
                                                                &g_ssStatus
                                                            )
                                    )
                                    {
                                        if  (       SERVICE_STOP_PENDING    
                                                ==  g_ssStatus.dwCurrentState
                                            )
                                            {
                                                wprintf (   TEXT    (   "."));
                                                Sleep( 1000 );
                                            }
                                        else
                                                break;
                                    }

                            if  (   SERVICE_STOPPED ==  g_ssStatus.dwCurrentState)
                                    wprintf (   TEXT    (   "\n%s stopped.\n"),
                                                pszName
                                            );
                            else
                                    wprintf (   TEXT    (   "\n%s failed to stop.\n"),
                                                pszName
                                            );

                        }

                CloseServiceHandle  (   schService);
            }
            else
                wprintf (   TEXT    (   "OpenService failed - %s\n"),
                            GetLastErrorText    (   g_szErr,    ERROR_BUFSZ)
                        );

            CloseServiceHandle  (   schSCManager);
        }
    else
            wprintf (   TEXT    (   "OpenSCManager failed - %s\n"),
                        GetLastErrorText    (   g_szErr,    ERROR_BUFSZ)
                    );
}
0
 
LVL 30

Author Comment

by:Axter
ID: 16553037
0
 
LVL 86

Expert Comment

by:jkr
ID: 16553054
BTW, the above is taken from "production" code, you'll find some other useful code at e.g. http://www.microsoft.com/msj/0298/service.aspx ("Manipulate Windows NT Services by Writing a Service Control Program") and/or http://www.codeproject.com/system/AMFSServiceManager.asp ("MFS Service Manger")
0
Granular recovery for Microsoft Exchange

With Veeam Explorer for Microsoft Exchange you can choose the Exchange Servers and restore points you’re interested in, and Veeam Explorer will present the contents of those mailbox stores for browsing, searching and exporting.

 
LVL 86

Expert Comment

by:jkr
ID: 16553071
Don't laugh at me, but that was the link I was looking for between my two comments *s*

Oh, and there it finally is, the 1M in Windows Programming... so many thanks back ;o)
0
 
LVL 30

Author Comment

by:Axter
ID: 16553098
I shouldn't have close the question so quickly, because there's still one problem I'm having with this code.

I had to change the following code to get it to compile:
 if (!QueryServiceStatusEx(
  schService,             // handle to service
  SC_STATUS_PROCESS_INFO, // info level
  (LPBYTE)&ssStatus,              // address of structure
  sizeof(SERVICE_STATUS_PROCESS), // size of structure
  &dwBytesNeeded ) )              // if buffer too small
 {
  return 0;
 }

I had to add the type casting for ssStatus.

I'm currently compiling this to 32bit windows, so it's currently not a problem, but in the future, I plan to port the code to 64bit windows.

How can I modify the code so that it will safely compile to a 64bit platform.

Here's the error I'm getting with the original code:

[QUOTE]serviceMain.cpp(259): error C2664: 'QueryServiceStatusEx' : cannot convert parameter 3 from 'SERVICE_STATUS_PROCESS' to 'LPBYTE'[/QUOTE]

0
 
LVL 86

Expert Comment

by:jkr
ID: 16553290
Sorry for the delay - is that what you get when compiling with Win64 error checking enabled? Let me dig out the conversion routines...
0
 
LVL 86

Expert Comment

by:jkr
ID: 16553350
Hm, using /Wp64 I don't get any errors with

#include <windows.h>

int main ()
{
SERVICE_STATUS_PROCESS ssStatus;
DWORD dwBytesNeeded;
SC_HANDLE schService = NULL;

//...

 if (!QueryServiceStatusEx(
  schService,             // handle to service
  SC_STATUS_PROCESS_INFO, // info level
  (LPBYTE)&ssStatus,              // address of structure
  sizeof(SERVICE_STATUS_PROCESS), // size of structure
  &dwBytesNeeded ) )              // if buffer too small
 {
  return 0;
 }

return 0;
}
0
 
LVL 30

Author Comment

by:Axter
ID: 16553384
>>is that what you get when compiling with Win64 error checking enabled?
Yes
I have the following compile option:
Yes (/Wp64)


>>Hm, using /Wp64 I don't get any errors with

Yes, but you're type casting.
I don't get the error when I type cast.  I get it when I remove the type cast.
I'm worried the type cast is just covering up a potential 64bit problem.
0
 
LVL 86

Expert Comment

by:jkr
ID: 16553428
Well, you have to type cast anyway, without that, even a 32bit app won't compile. The type cast only isn't necessary when you compile that code as .c and not .cpp - /Wp64 isn't really the reason here.
0
 
LVL 30

Author Comment

by:Axter
ID: 16553467
>>Well, you have to type cast anyway, without that, even a 32bit app won't compile.

Never mind.  I was having a brain fart! :-)

Sometimes you just can't see the forest for the trees....
0
 
LVL 86

Expert Comment

by:jkr
ID: 16553487
That's an obviously universal proverb - and sometimes *so* true. Noone is immune to that ;o)
0

Featured Post

Transaction-level recovery for Oracle database

Veeam Explore for Oracle delivers low RTOs and RPOs with agentless transaction log backup and transaction-level recovery of Oracle databases. You can restore the database to a precise point in time, even to a specific transaction.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes a technique for converting RTF (Rich Text Format) data to HTML and provides C++ source that does it all in just a few lines of code. Although RTF is coming to be considered a "legacy" format, it is still in common use... po…
A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in an application. Themes can be made up of a set of elements: skins, style sheets, images, and o…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…

581 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question