PDA

View Full Version : نحوه نوشتن و ايجاد كردن سرويس ها



Yasersadegh
سه شنبه 23 تیر 1388, 18:22 عصر
با سلام
من يه برنامه نوشتم كه مي خوام هر بار كه ويندوز بالا اومد برنامم اجرا بشه!!
برايه اينكار از طريق رجيستري عمل كردم و كار ميكنه!!
ولي حالا مي خوام اين كارو از طريق سرويس ها انجام بدم!!:لبخندساده:
من چطوري مي تونم يه سرويس ايجاد كنم و استارتش كنم!!؟:متفکر:
از دوستان ممنون ميشم اگه يه توضيحي ، مقاله اي كه نحوه ايجاد و استارت كردن يه سرويس رو توضيح ميده بفرمايند و يا اگه نمونه كدي دارن بزارن كه ديگه خيلي عاليه!!:خجالت:

tdkhakpur
سه شنبه 23 تیر 1388, 22:30 عصر
سلام
خوب برنامه سرویس را بسازید سپس کامپایل کرده و در رجیستری ثبت کنید.
ولی در مورد استارت مقاله لازم نیست شما در برنامتون در هنگام اجرا و شروع به کارسرویس را open یا Active کنید

Yasersadegh
چهارشنبه 24 تیر 1388, 08:39 صبح
دوست عزيز ممنون ولي وقتي من سرويسي رو مي نويسم و در ليست سرويس هاي ويندوز اضافه ميشه وقتي كه استارتش مي كنم در حالت pending باقي مي مونه واستارت نميشه!!
برايه اين كه استارت بشه نياز هست كه يكسري توابع به برنامه اضافه بشه!! من نمي دونم كه چه توابعي اضافه كنم و چه دستوراني بايد داشته باشند اين توابع!!:متفکر:
اگه دوستان كمك و راهنمايي بفرمايند ممنون ميشم!!:خجالت:

sasan_vm
چهارشنبه 24 تیر 1388, 09:43 صبح
سلام
این توابع با استفاده از API نوشتم برای start, stop, register ,... سرویس ها است.
موفق باشید:


//------------------------------------------------------------------------------
bool __fastcall IsServiceStarted(const AnsiString& sService)
{
bool Result;
SC_HANDLE ServiceManager;
SC_HANDLE ServiceHandle;
__try
{
try
{
SERVICE_STATUS SrvStatus;
ServiceManager = NULL;
ServiceHandle = NULL;
Result = false;
SrvStatus.dwCurrentState = -1;
ServiceManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if ( ServiceManager )
{
ServiceHandle = OpenService(ServiceManager, sService.c_str(), SERVICE_QUERY_STATUS);
if ( ServiceHandle )
{
if ( QueryServiceStatus(ServiceHandle, &SrvStatus) )
{
Result = (SrvStatus.dwCurrentState == SERVICE_RUNNING);
}
CloseServiceHandle(ServiceHandle);
ServiceHandle = NULL;
}
CloseServiceHandle(ServiceManager);
ServiceManager = NULL;
}
}
catch (Exception &e)
{
throw Exception(e.Message);
}
}
__finally
{
if (ServiceHandle)
CloseServiceHandle(ServiceHandle);
if (ServiceManager)
CloseServiceHandle(ServiceManager);
}
return Result;
}
//------------------------------------------------------------------------------
bool __fastcall IsServiceExist(const AnsiString& sService)
{
bool Result;
SC_HANDLE ServiceManager;
SC_HANDLE ServiceHandle;
__try
{
try
{
ServiceManager = NULL;
ServiceHandle = NULL;
Result = false;
ServiceManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if ( ServiceManager )
{
ServiceHandle = OpenService(ServiceManager, sService.c_str(), SERVICE_QUERY_STATUS);
Result = ServiceHandle;
if ( ServiceHandle )
{
CloseServiceHandle(ServiceHandle);
ServiceHandle = NULL;
}
CloseServiceHandle(ServiceManager);
ServiceManager = NULL;
}
}
catch (Exception &e)
{
throw Exception(e.Message);
}
}
__finally
{
if (ServiceHandle)
CloseServiceHandle(ServiceHandle);
if (ServiceManager)
CloseServiceHandle(ServiceManager);
}
return Result;
}
//------------------------------------------------------------------------------
bool __fastcall UnregisterService(const AnsiString& sService)
{
bool Result;
SC_HANDLE ServiceManager;
SC_HANDLE ServiceHandle;
__try
{
try
{
ServiceManager = NULL;
ServiceHandle = NULL;
Result = false;
StopService(sService);
ServiceManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if ( ServiceManager )
{
ServiceHandle = OpenService(ServiceManager, sService.c_str(), DELETE);
if ( ServiceHandle )
{
Result = DeleteService(ServiceHandle);
CloseServiceHandle(ServiceHandle);
ServiceHandle = NULL;
}
CloseServiceHandle(ServiceManager);
ServiceManager = NULL;
}
}
catch (Exception &e)
{
// throw Exception(e.Message);
}
}
__finally
{
if (ServiceHandle)
CloseServiceHandle(ServiceHandle);
if (ServiceManager)
CloseServiceHandle(ServiceManager);
}
return Result;
}
//------------------------------------------------------------------------------
bool __fastcall RegisterService(const AnsiString& sPath, const AnsiString& sService, LPTSTR lpDescription, LPCTSTR lpDependencies, bool Start)
{
bool Result;
SC_HANDLE ServiceManager;
SC_HANDLE ServiceHandle;
__try
{
try
{
ServiceManager = NULL;
ServiceHandle = NULL;
Result = false;
ServiceManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if ( ServiceManager )
{
ServiceHandle = CreateService(
ServiceManager, // SCManager database
sService.c_str(), // name of service
sService.c_str(), // service name to display
SERVICE_ALL_ACCESS, // desired access
SERVICE_WIN32_OWN_PROCESS, // service type
SERVICE_AUTO_START, // start type
SERVICE_ERROR_NORMAL, // error control type
sPath.c_str(), // service's binary
NULL, // no load ordering group
NULL, // no tag identifier
lpDependencies, // no dependencies null
NULL, // LocalSystem account
NULL); // no password
if ( ServiceHandle )
{
if (lpDescription != NULL) // Add service description
{
SERVICE_DESCRIPTION SrvDesc;
SrvDesc.lpDescription = lpDescription;
ChangeServiceConfig2(ServiceHandle, SERVICE_CONFIG_DESCRIPTION, &SrvDesc);
}
Result = true;
CloseServiceHandle(ServiceHandle);
ServiceHandle = NULL;
}
CloseServiceHandle(ServiceManager);
ServiceManager = NULL;
}
}
catch (Exception &e)
{
throw Exception(e.Message);
}
}
__finally
{
if (ServiceHandle)
CloseServiceHandle(ServiceHandle);
if (ServiceManager)
CloseServiceHandle(ServiceManager);
}
if (Start && Result)
Result = StartService(sService);
return Result;
}
//------------------------------------------------------------------------------
bool __fastcall StartService(const AnsiString& sService)
{
bool Result;
SERVICE_STATUS SrvStatus;
SC_HANDLE ServiceManager;
SC_HANDLE ServiceHandle;
DWORD dwOldCheckPoint;
DWORD dwStartTickCount;
DWORD dwWaitTime;
DWORD dwStatus;
try
{
ServiceManager = NULL;
ServiceHandle = NULL;
Result = false;
ServiceManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if ( ServiceManager )
{
ServiceHandle = OpenService(ServiceManager, sService.c_str(), SERVICE_ALL_ACCESS);
if (ServiceHandle)
{
if ( !StartService(
ServiceHandle, // handle to service
0, // number of arguments
NULL) ) // no arguments
throw Exception("Error: starting service.");
if ( !QueryServiceStatus(
ServiceHandle, // handle to service
&SrvStatus) ) // address of status information structure
throw Exception("Error: query service status.");
dwStartTickCount = GetTickCount();
dwOldCheckPoint = SrvStatus.dwCheckPoint;
while ( SrvStatus.dwCurrentState == SERVICE_START_PENDING )
{
// Do not wait longer than the wait hint. A good interval is
// one tenth the wait hint, but no less than 1 second and no
// more than 10 seconds.
dwWaitTime = SrvStatus.dwWaitHint / 10;
if( dwWaitTime < 1000 )
dwWaitTime = 1000;
else if ( dwWaitTime > 10000 )
dwWaitTime = 10000;
Sleep( dwWaitTime );
// Check the status again.
if ( !QueryServiceStatus(
ServiceHandle, // handle to service
&SrvStatus) ) // address of structure
break;
if ( SrvStatus.dwCheckPoint > dwOldCheckPoint )
{
// The service is making progress.
dwStartTickCount = GetTickCount();
dwOldCheckPoint = SrvStatus.dwCheckPoint;
}
else
{
if( GetTickCount() - dwStartTickCount > SrvStatus.dwWaitHint )
{
// No progress made within the wait hint
break;
}
}
}
Result = (SrvStatus.dwCurrentState == SERVICE_RUNNING);
}
}
}
catch (...)
{
}
return Result;
}
//------------------------------------------------------------------------------
bool __fastcall StopService(const AnsiString& sService, bool StopDependencies)
{
bool Result;
SERVICE_STATUS SrvStatus;
SC_HANDLE ServiceManager;
SC_HANDLE ServiceHandle;
DWORD dwTimeout;
DWORD dwStartTime;

__try
{
try
{
ServiceManager = NULL;
ServiceHandle = NULL;
Result = false;
ServiceManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if ( ServiceManager )
{
ServiceHandle = OpenService(ServiceManager, sService.c_str(), SERVICE_STOP | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS);
if ( ServiceHandle )
{
dwTimeout = 30000;
dwStartTime = GetTickCount();
if ( !QueryServiceStatus( ServiceHandle, &SrvStatus ) )
throw Exception("Error: Query service status.");
Result = ( SrvStatus.dwCurrentState == SERVICE_STOPPED );
if ( !Result ) // try to stop service
{
while ( SrvStatus.dwCurrentState == SERVICE_STOP_PENDING )
{
Sleep( SrvStatus.dwWaitHint );
if ( !QueryServiceStatus( ServiceHandle, &SrvStatus ) )
throw Exception("Error: Query service status.");
if ( SrvStatus.dwCurrentState == SERVICE_STOPPED )
{
Result = true;
break;
}
if ( GetTickCount() - dwStartTime > dwTimeout )
throw Exception("Error: Time out.");
}
// If the service is running, dependencies must be stopped first
if ( !Result && StopDependencies )
{
DWORD i;
DWORD dwBytesNeeded;
DWORD dwCount;
LPENUM_SERVICE_STATUS lpDependencies = NULL;
ENUM_SERVICE_STATUS ess;
SC_HANDLE hDepService;
// Pass a zero-length buffer to get the required buffer size
if ( EnumDependentServices( ServiceHandle, SERVICE_ACTIVE, lpDependencies, 0, &dwBytesNeeded, &dwCount ) )
{
// If the Enum call succeeds, then there are no dependent
// services so do nothing
}
else
{
if ( GetLastError() != ERROR_MORE_DATA )
throw Exception("Unexpected error.");
// Allocate a buffer for the dependencies
lpDependencies = (LPENUM_SERVICE_STATUS) HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, dwBytesNeeded );
if ( !lpDependencies )
throw Exception("Error: Out of memory.");
__try
{
// Enumerate the dependencies
if ( !EnumDependentServices(ServiceHandle, SERVICE_ACTIVE, lpDependencies, dwBytesNeeded, &dwBytesNeeded, &dwCount) )
throw Exception("Error: Enumerate the dependencies.");
for ( i = 0; i < dwCount; i++ )
{
ess = *(lpDependencies + i);
// Open the service
hDepService = OpenService(ServiceManager, ess.lpServiceName, SERVICE_STOP | SERVICE_QUERY_STATUS);
if ( !hDepService )
throw Exception("Error: Open dependencies service.");
__try
{
// Send a stop code
if ( !ControlService(hDepService, SERVICE_CONTROL_STOP, &SrvStatus) )
throw Exception("Error: Send a stop code.");
// Wait for the service to stop
while ( SrvStatus.dwCurrentState != SERVICE_STOPPED )
{
Sleep( SrvStatus.dwWaitHint );
if ( !QueryServiceStatus( hDepService, &SrvStatus ) )
throw Exception("Error: Query service status.");
if ( SrvStatus.dwCurrentState == SERVICE_STOPPED )
break;
if ( GetTickCount() - dwStartTime > dwTimeout )
throw Exception("Error: Time out.");
}
}
__finally
{
// Always release the service handle
CloseServiceHandle( hDepService );
}
}
}
__finally
{
// Always free the enumeration buffer
HeapFree( GetProcessHeap(), 0, lpDependencies );
}
}
}
// Send a stop code to the main service
if ( !Result )
{
if ( !ControlService(ServiceHandle, SERVICE_CONTROL_STOP, &SrvStatus ) )
throw Exception("Error: Control service.");
// Wait for the service to stop
while ( SrvStatus.dwCurrentState != SERVICE_STOPPED )
{
Sleep( SrvStatus.dwWaitHint );
if ( !QueryServiceStatus( ServiceHandle, &SrvStatus ) )
throw Exception("Error: Query service status.");
if ( SrvStatus.dwCurrentState == SERVICE_STOPPED )
{
Result = true;
break;
}
if ( GetTickCount() - dwStartTime > dwTimeout )
throw Exception("Error: Time out.");
}
}
}
CloseServiceHandle(ServiceHandle);
ServiceHandle = NULL;
}
CloseServiceHandle(ServiceManager);
ServiceManager = NULL;
}
}
catch (Exception &e)
{
throw Exception(e.Message);
}
}
__finally
{
if (ServiceHandle)
CloseServiceHandle(ServiceHandle);
if (ServiceManager)
CloseServiceHandle(ServiceManager);
}
return Result;
}
//------------------------------------------------------------------------------

Yasersadegh
سه شنبه 13 مرداد 1388, 10:04 صبح
ممنون از دوستان عزيز به خاطر راهنمايي ها تون
ولي من اين كد رو نوشتم كه بازم برايه استارت كردن اين سرويس ارور 1053 و 1063 رو ميده.!!
بخشي از كدي كه نوشتم به صورت زير هست:



bool RegisterService(WCHAR* sPath, WCHAR* sService, bool Start)
{
bool Result;
SC_HANDLE ServiceManager;
SC_HANDLE ServiceHandle;
ServiceManager = NULL;
ServiceHandle = NULL;
Result = false;
ServiceManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if ( ServiceManager )
{
ServiceHandle = CreateService(
ServiceManager, // SCManager database
sService, // name of service
sService, // service name to display
SERVICE_ALL_ACCESS, // desired access
SERVICE_WIN32_OWN_PROCESS, // service type
SERVICE_AUTO_START, // start type
SERVICE_ERROR_NORMAL, // error control type
sPath,// service's binary
NULL, // no load ordering group
NULL, // no tag identifier
NULL, // no dependencies null
NULL, // LocalSystem account
NULL);// no password
if ( ServiceHandle )
{
Result = true;
SERVICE_TABLE_ENTRY DisTable[] =
{
{ sService, (LPSERVICE_MAIN_FUNCTION)StartService },
{ NULL, NULL }
};

if (!StartServiceCtrlDispatcher( DisTable ))
{
// Show Error
printf("\nStartServiceCtrlDispatcher failed (%d)\n", GetLastError());
}
if (Start && Result)
Result = StartService(
ServiceHandle, // handle to service
0, // number of arguments
NULL);
if(!Result)
{
printf("\n Error %d",GetLastError());
getch();
}
CloseServiceHandle(ServiceHandle);
ServiceHandle = NULL;
}
CloseServiceHandle(ServiceManager);
ServiceManager = NULL;
}

return Result;
}
bool UnregisterService(WCHAR* sService)
{
bool Result;
SC_HANDLE ServiceManager;
SC_HANDLE ServiceHandle;
ServiceManager = NULL;
ServiceHandle = NULL;
Result = false;
StopService(sService);
ServiceManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if ( ServiceManager )
{
ServiceHandle = OpenService(ServiceManager, sService, DELETE);
if ( ServiceHandle )
{
Result = DeleteService(ServiceHandle);
if(!Result)
{
printf("\n Error %d",GetLastError());
getch();
}
CloseServiceHandle(ServiceHandle);
ServiceHandle = NULL;
}
CloseServiceHandle(ServiceManager);
ServiceManager = NULL;
}
return Result;
}


bool StartService (WCHAR* sService)
{
bool Result;
SERVICE_STATUS SrvStatus;
SC_HANDLE ServiceManager;
SC_HANDLE ServiceHandle;
DWORD dwOldCheckPoint;
DWORD dwStartTickCount;
DWORD dwWaitTime;
DWORD dwStatus;
ServiceManager = NULL;
ServiceHandle = NULL;
Result = false;
ServiceManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if ( ServiceManager )
{
ServiceHandle = OpenService(ServiceManager, sService, SERVICE_ALL_ACCESS);
if (ServiceHandle)
{
if ( !StartService(
ServiceHandle, // handle to service
0, // number of arguments
NULL) ) // no arguments
{
printf("\n Error %d",GetLastError());
getch();
return Result;
}
if ( !QueryServiceStatus(
ServiceHandle, // handle to service
&SrvStatus) ) // address of status information structure
{
return Result;
}
dwStartTickCount = GetTickCount();
dwOldCheckPoint = SrvStatus.dwCheckPoint;
while ( SrvStatus.dwCurrentState == SERVICE_START_PENDING )
{
// Do not wait longer than the wait hint. A good interval is
// one tenth the wait hint, but no less than 1 second and no
// more than 10 seconds.
dwWaitTime = SrvStatus.dwWaitHint / 10;
if( dwWaitTime < 1000 )
dwWaitTime = 1000;
else if ( dwWaitTime > 10000 )
dwWaitTime = 10000;
Sleep( dwWaitTime );
// Check the status again.
if ( !QueryServiceStatus(
ServiceHandle, // handle to service
&SrvStatus) ) // address of structure
{
break;
}
if ( SrvStatus.dwCheckPoint > dwOldCheckPoint )
{
// The service is making progress.
dwStartTickCount = GetTickCount();
dwOldCheckPoint = SrvStatus.dwCheckPoint;
}
else
{
if( GetTickCount() - dwStartTickCount > SrvStatus.dwWaitHint )
{
// No progress made within the wait hint
break;
}
}
}
Result = (SrvStatus.dwCurrentState == SERVICE_RUNNING);
}
}
return Result;
}

در اين كد من در تابع main وقتي تابع registerservice رو فراخواني مي كنم برايه استارت كردنش ارورهايي كه اشاره كردم رو تابع getlasterror برميگردونه!!:متفکر:
نمي دونم مشكل چيه!!؟:عصبانی++:
لطفا كمك كنيد!!:خجالت:

sasan_vm
سه شنبه 13 مرداد 1388, 10:43 صبح
خطای 1053: زمان start/stop سرویس از زمانی که در نظر گرفته اید بیشتر طول میکشه (WaitHint در کد سرویس) [http://support.microsoft.com/kb/839174]
احتمال دارد سرویس نوشته شده هم مشکل داشته باشد:
- سرویس نوشته شده را با سرویس کنترلر (sc) ویندوز نصب کنید
- یک سرویس سالم را با کد خودتان نصب کنید