Hi...
I want to create windows service for my abc.exe through programaticaly in c or c++
how to do this???

So how many links did you actually read before giving up?
Because you spent at most 17 MINUTES before deciding that you needed to reply.

In my code it gives error like

if (!StartService(
            schService,  
            0,          
            NULL) )     
    {
            printf("Hello");
        printf("\nStartService failed (%d)\n", GetLastError());
        CloseServiceHandle(schService); 
        CloseServiceHandle(schSCManager);
        return; 
    }

It gives error start service failed 1053

#include <windows.h>
#include <stdio.h>
#include<conio.h>

#define szSvcName TEXT("abc")
#define SVCNAME TEXT("abc")
SC_HANDLE schSCManager;
SC_HANDLE schService;
VOID DoStartSvc();

VOID SvcInstall()
{
    SC_HANDLE schSCManager;
    SC_HANDLE schService;
    TCHAR szPath[MAX_PATH];

    if( !GetModuleFileName( NULL, szPath, MAX_PATH ) )
    {
        printf("Cannot install service (%d)\n", GetLastError());
        return;
    }

      schSCManager = OpenSCManager( 
        NULL, NULL,     SC_MANAGER_ALL_ACCESS);  
 
    if (NULL == schSCManager) 
    {
        printf("OpenSCManager failed (%d)\n", GetLastError());
        return;
    }

       schService = CreateService( 
        schSCManager,              
        SVCNAME,                  
        SVCNAME,                   
        SERVICE_ALL_ACCESS,       
        SERVICE_WIN32_OWN_PROCESS,
        SERVICE_AUTO_START ,      
        SERVICE_ERROR_NORMAL,     
        szPath,                   
        NULL,                      
        NULL,                      
        NULL,                     
        NULL,                    
        NULL);                   
 
    if (schService == NULL) 
    {
        printf("CreateService failed (%d)\n", GetLastError()); 
        CloseServiceHandle(schSCManager);
        return;
    }
    else printf("Service installed successfully\n"); 
    DoStartSvc();
    CloseServiceHandle(schService); 
    CloseServiceHandle(schSCManager);
     return;
}

VOID DoStartSvc()
{
     printf("\nIn DoStart");
    SERVICE_STATUS_PROCESS ssStatus; 
    DWORD dwOldCheckPoint; 
    DWORD dwStartTickCount;
    DWORD dwWaitTime;
    DWORD dwBytesNeeded;

    schSCManager = OpenSCManager( 
        NULL,                    
        NULL,                    
        SC_MANAGER_ALL_ACCESS);  
 
    if (NULL == schSCManager) 
    {
        printf("OpenSCManager failed (%d)\n", GetLastError());
        return;
    }

       printf("\nIn open service");
    schService = OpenService( 
        schSCManager,         
        szSvcName,            
        SERVICE_ALL_ACCESS); 
    if (schService == NULL)
    { 
        printf("OpenService failed (%d)\n", GetLastError()); 
        printf("\nIn service Null");
        CloseServiceHandle(schSCManager);
        return;
    }    

       if (!QueryServiceStatusEx( 
            schService,                     
            SC_STATUS_PROCESS_INFO,         
            (LPBYTE) &ssStatus,            
            sizeof(SERVICE_STATUS_PROCESS),
            &dwBytesNeeded ) )             
    {
        printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
        
        CloseServiceHandle(schService); 
        CloseServiceHandle(schSCManager);
        return; 
    }

        if(ssStatus.dwCurrentState != SERVICE_STOPPED && ssStatus.dwCurrentState != SERVICE_STOP_PENDING)
    {
        printf("Cannot start the service because it is already running\n");
        CloseServiceHandle(schService); 
        CloseServiceHandle(schSCManager);
        return; 
    }

    while (ssStatus.dwCurrentState == SERVICE_STOP_PENDING)
    {
               dwStartTickCount = GetTickCount();
        dwOldCheckPoint = ssStatus.dwCheckPoint;

       
        dwWaitTime = ssStatus.dwWaitHint / 10;

        if( dwWaitTime < 1000 )
            dwWaitTime = 1000;
        else if ( dwWaitTime > 10000 )
            dwWaitTime = 10000;

        Sleep( dwWaitTime );

        
        if (!QueryServiceStatusEx( 
                schService,                    
                SC_STATUS_PROCESS_INFO,         
                (LPBYTE) &ssStatus,        
                sizeof(SERVICE_STATUS_PROCESS), 
                &dwBytesNeeded ) )             
        {
            printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
            CloseServiceHandle(schService); 
            CloseServiceHandle(schSCManager);
            return; 
        }

        if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
        {
                  dwStartTickCount = GetTickCount();
            dwOldCheckPoint = ssStatus.dwCheckPoint;
        }
        else
        {
            if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint)
            {
                printf("Timeout waiting for service to stop\n");
                CloseServiceHandle(schService); 
                CloseServiceHandle(schSCManager);
                return; 
            }
        }
    }

     if (!StartService(
            schService,  
            0,           
            NULL) )      
    {
            printf("Hello");
        printf("\nStartService failed (%d)\n", GetLastError());
        CloseServiceHandle(schService); 
        CloseServiceHandle(schSCManager);
        return; 
    }
    else printf("Service start pending...\n"); 

    
 
    if (!QueryServiceStatusEx( 
            schService,                    
            SC_STATUS_PROCESS_INFO,         
            (LPBYTE) &ssStatus,           
            sizeof(SERVICE_STATUS_PROCESS), 
            &dwBytesNeeded ) )              
    {
        printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
        CloseServiceHandle(schService); 
        CloseServiceHandle(schSCManager);
        return; 
    }
       dwStartTickCount = GetTickCount();
    dwOldCheckPoint = ssStatus.dwCheckPoint;

    while (ssStatus.dwCurrentState == SERVICE_START_PENDING) 
    { 
       
 
        dwWaitTime = ssStatus.dwWaitHint / 10;

        if( dwWaitTime < 1000 )
            dwWaitTime = 1000;
        else if ( dwWaitTime > 10000 )
            dwWaitTime = 10000;

        Sleep( dwWaitTime );

         if (!QueryServiceStatusEx( 
            schService,            
            SC_STATUS_PROCESS_INFO, 
            (LPBYTE) &ssStatus,            
            sizeof(SERVICE_STATUS_PROCESS), 
            &dwBytesNeeded ) )              
        {
            printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
            break; 
        }
 
        if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
        {
                        dwStartTickCount = GetTickCount();
            dwOldCheckPoint = ssStatus.dwCheckPoint;
        }
        else
        {
            if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint)
            {
               
                break;
            }
        }
    } 

       if (ssStatus.dwCurrentState == SERVICE_RUNNING) 
    {
        printf("Service started successfully.\n"); 
    }
    else 
    { 
        printf("Service not started. \n");
        printf("  Current State: %d\n", ssStatus.dwCurrentState); 
        printf("  Exit Code: %d\n", ssStatus.dwWin32ExitCode); 
        printf("  Check Point: %d\n", ssStatus.dwCheckPoint); 
        printf("  Wait Hint: %d\n", ssStatus.dwWaitHint); 
    } 

    CloseServiceHandle(schService); 
    CloseServiceHandle(schSCManager);
}


int main()
{
    SvcInstall();
   
       getch();
}

Actually this code from msdn .. i m trying to execute this code for my exe

Actually this code from msdn.

No way! I thought you made it yourself ;)

Anyway: #define szSvcName TEXT("abc") "abc" isn't really a service is it? So it can't be started.

These kind programs are quite difficult for a beginner. (your getch() gave you away)
I suggest you start of with some simpler programs...

#include<windows.h>
#include<stdio.h>

#define SLEEP_TIME 300000

SERVICE_STATUS          ServiceStatus; 
SERVICE_STATUS_HANDLE   hStatus; 
 
void  ServiceMain(int argc, char** argv); 
void  ControlHandler(DWORD request); 

int executeLoop()
{     
      
      try{
       system("driverquery.exe>>c:\\abc.txt");
       }catch (int e)
       {
       printf(" Error in Executeloop %d",e);       
       return 0;       
       }
       
      return 1;     
}

void ServiceMain(int argc, char** argv) 
{ 
   int error; 
   ServiceStatus.dwServiceType =SERVICE_WIN32; 
   ServiceStatus.dwCurrentState = SERVICE_START_PENDING; 
   ServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
   ServiceStatus.dwWin32ExitCode = 0; 
   ServiceStatus.dwServiceSpecificExitCode = 0; 
   ServiceStatus.dwCheckPoint = 0; 
   ServiceStatus.dwWaitHint = 0; 
 
   hStatus = RegisterServiceCtrlHandler("Client",(LPHANDLER_FUNCTION)ControlHandler); 
   if (hStatus == (SERVICE_STATUS_HANDLE)0) 
   { 
      // Registering Control Handler failed
      return; 
   }  
   // Initialize Service 
   error = 0; 
   if (error) 
   {
      // Initialization failed
      ServiceStatus.dwCurrentState = SERVICE_STOPPED; 
      ServiceStatus.dwWin32ExitCode = 1; 
      SetServiceStatus(hStatus, &ServiceStatus); 
      return; 
   } 
   // We report the running status to SCM. 
   ServiceStatus.dwCurrentState = SERVICE_RUNNING; 
   SetServiceStatus (hStatus, &ServiceStatus);
 
   // The worker loop of a service
   while (ServiceStatus.dwCurrentState ==   SERVICE_RUNNING)
   {
 
      int result=0;
      result = executeLoop();
      //result=1;
      if (result)
      {
         ServiceStatus.dwCurrentState =  SERVICE_STOPPED; 
         ServiceStatus.dwWin32ExitCode      = 1; 
         SetServiceStatus(hStatus,  &ServiceStatus);
         return;
      }
      Sleep(SLEEP_TIME);
   }
   return; 
}
void ControlHandler(DWORD request) 
{ 
   switch(request) 
   { 
      case SERVICE_CONTROL_STOP: 
         ServiceStatus.dwWin32ExitCode = 0; 
         ServiceStatus.dwCurrentState = SERVICE_STOPPED; 
         SetServiceStatus (hStatus, &ServiceStatus);
         return; 
 
      case SERVICE_CONTROL_SHUTDOWN: 
         ServiceStatus.dwWin32ExitCode = 0; 
         ServiceStatus.dwCurrentState = SERVICE_STOPPED; 
         SetServiceStatus (hStatus, &ServiceStatus);
         return; 
        
      default:
         break;
    }  
    // Report current status
    SetServiceStatus (hStatus, &ServiceStatus);
 
    return; 
}

int main()
{
       SERVICE_TABLE_ENTRY ServiceTable[2];
       ServiceTable[0].lpServiceName = "Client";
       ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
       ServiceTable[1].lpServiceName = NULL;
       ServiceTable[1].lpServiceProc = NULL;
       // Start the control dispatcher thread for our service
       StartServiceCtrlDispatcher(ServiceTable);  
       return 0;
}

service not starting...automatic ....
i m giving sleep time also..but no data in abc.txt

yes ....
i m executing this command...
sc create Client binpath=c:\windows\system32\123.exe type= own start= auto

#include<windows.h>
#include<stdio.h>

#define SLEEP_TIME 300000

SERVICE_STATUS          ServiceStatus; 
SERVICE_STATUS_HANDLE   hStatus; 
 
void  ServiceMain(int argc, char** argv); 
void  ControlHandler(DWORD request); 

int executeLoop()
{     
      int a;
      try
      {
            system("driverquery.exe>>c:\\abc.txt");
      }
      catch (int e)
      {
           printf(" Error in Executeloop %d",e);  
           executeLoop();     
       ///a=0;       
      }
       
       //a=1;     
      //if (a==1)
      //{
         ServiceStatus.dwCurrentState =  SERVICE_STOPPED; 
         ServiceStatus.dwWin32ExitCode      = 0; 
         SetServiceStatus(hStatus,  &ServiceStatus);
        
    //  }
     // return;
}

void ServiceMain(int argc, char** argv) 
{ 
   Sleep(SLEEP_TIME);
   int error; 
   ServiceStatus.dwServiceType =SERVICE_WIN32; 
   ServiceStatus.dwCurrentState = SERVICE_START_PENDING; 
   ServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
   ServiceStatus.dwWin32ExitCode = 0; 
   ServiceStatus.dwServiceSpecificExitCode = 0; 
   ServiceStatus.dwCheckPoint = 0; 
   ServiceStatus.dwWaitHint = 0; 
 
   hStatus = RegisterServiceCtrlHandler("Client",(LPHANDLER_FUNCTION)ControlHandler); 
   if (hStatus == (SERVICE_STATUS_HANDLE)0) 
   { 
      // Registering Control Handler failed
      return; 
   }  
   // Initialize Service 
   error = 0; 
   if (error) 
   {
      // Initialization failed
      ServiceStatus.dwCurrentState = SERVICE_STOPPED; 
      ServiceStatus.dwWin32ExitCode = 1; 
      SetServiceStatus(hStatus, &ServiceStatus); 
      return; 
   } 
   // We report the running status to SCM. 
   ServiceStatus.dwCurrentState = SERVICE_RUNNING; 
   SetServiceStatus (hStatus, &ServiceStatus);
 
   // The worker loop of a service
   while (ServiceStatus.dwCurrentState ==   SERVICE_RUNNING)
   {
 
      int result=0;
      result = executeLoop();
      exit(0);
      //result=1;
      /*if (result==1)
      {
         ServiceStatus.dwCurrentState =  SERVICE_STOPPED; 
         ServiceStatus.dwWin32ExitCode      = 1; 
         SetServiceStatus(hStatus,  &ServiceStatus);
         return;
      }*/
      
      
      
   }
   return; 
}
void ControlHandler(DWORD request) 
{ 
   switch(request) 
   { 
      case SERVICE_CONTROL_STOP: 
         ServiceStatus.dwWin32ExitCode = 0; 
         ServiceStatus.dwCurrentState = SERVICE_STOPPED; 
         SetServiceStatus (hStatus, &ServiceStatus);
         return; 
 
      case SERVICE_CONTROL_SHUTDOWN: 
         ServiceStatus.dwWin32ExitCode = 0; 
         ServiceStatus.dwCurrentState = SERVICE_STOPPED; 
         SetServiceStatus (hStatus, &ServiceStatus);
         return; 
        
      default:
         break;
    }  
    // Report current status
    SetServiceStatus (hStatus, &ServiceStatus);
 
    return; 
}

int main()
{
       SERVICE_TABLE_ENTRY ServiceTable[2];
       ServiceTable[0].lpServiceName = "Client";
       ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
       ServiceTable[1].lpServiceName = NULL;
       ServiceTable[1].lpServiceProc = NULL;
       // Start the control dispatcher thread for our service
       StartServiceCtrlDispatcher(ServiceTable);  
       return 0;
}

I m modifying my code...
I m trying for ..when execute executeLoop service should stop..but when i m checking in services..it's status is still starting...not stoped..how to resolve this problem??

it's status is still starting

Your program failed to inform about the service's status, hence the sticky starting status.

First of all, remove Sleep(SLEEP_TIME); - you must call the RegisterServiceCtrlHandler() as quickly as possible, so the Sleep() is absolutely misplaced there. You may want to use Sleep() inside the service's worker loop though, i.e.

while (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
{
    // do some work ...
    executeLoop()

    // sleep a while
    Sleep(SLEEP_TIME);
}

Then, generally (since you are obviously experimenting) the program appears to be non-service-like, because it only tries executeLoop() once and immediately exits (if it ever gets there).
However, I think you should try to code as a service from the ground up though. I.e. let the worker while() loop continue as long as the service's status has not been changed from SERVICE_RUNNING or no fatal error(s) have occurred. To handle a fatal error, change the service's status (SetServiceStatus(...)) and break out of the worker while() loop, so the service will terminate properly. You do not need the exit() function.

Once you have coded the basic structure of the program so that you can reliably start/stop it from the Windows Services program, then start filling in the actual functionality that you have in mind.

As an aid in debugging, you could write debug output to a file, so that you have a trace of what actually happened and what not, i.e.

// global FILE * 
FILE * dbg_out = fopen("c:\\client_dbg.txt", "w");

int executeLoop()
{
    fprintf(dbg_out, "executeLoop: ...\n"); fflush(dbg_out);

    int status = some_func();

    fprintf(dbg_out, "executeLoop: exiting with code: [%d] \n", status); fflush(dbg_out);

    return status;
}

Last but not least, check the return codes of the functions you use (SetServiceStatus() etc), so you'll know where things start to go wrong. GetLastError() returns the most recent error code (see winerror.h) i.e.

if(FALSE == SetServiceStatus(...))
{
    // what is the error code
    DWORD dwErr = GetLastError();
    // write information to log or something alike ...
}
This article has been dead for over six months. Start a new discussion instead.