[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 503
  • Last Modified:

i make my application as service but it run moment and after that it stop why?

why my application  run  a second  and after that it close
what is the problem of that ?
please help  me
0
sa3q
Asked:
sa3q
  • 17
  • 13
  • 5
  • +2
3 Solutions
 
jazzIIIloveCommented:
Hi there;

Could you post the code of the service?

Is there a some kind of loop in your service to execute as an infinite manner?

Best regards.
0
 
magicdlfCommented:
Please also check the event viewer to see if there's any related log.
0
 
sa3qAuthor Commented:
i use the setup factory to  make that the script i use


and my code  have 2  threads  and  each  of the two  thread their  is  infinite loop

what  is  the problem  of that  ???
Service.Create("d:\\Program Files\\MYapp\\start.exe", "sa3qApp", "sa3qApp", SERVICE_WIN32_OWN_PROCESS, true, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, "", "", nil, "", "");

Open in new window

0
Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

 
3_SCommented:
In your program (start.exe) put some error logging to a file, this way you can better debug what is happening and where it stops.
0
 
sa3qAuthor Commented:
3_S:

how can i put some error logging ?????????
0
 
3_SCommented:
Use a try catch statement in your program
If you already have some error catch, put extra statement in the catch block to write the error to file.
If none use yet, put one around the code in your main.


try{
  Your code
}
catch( MyException ex )
{
  StreamWriter* pwriter = new StreamWriter(S"c:\\log.txt");
  pwriter->WriteLine(S"Error occured." + ex.Number + ":  " + ex.Message );
  pwriter->Close();
}

Open in new window

0
 
js-profiCommented:
Not only the threads must have an infinite loop but the service_main as well. Your service_main was called by SCM and should do a permanent job until terminated by SCM. That also is done by callback using the status function you provided with your call to SCM.
0
 
sa3qAuthor Commented:
httheir many problems  of the  code  
Error	4	error C2061: syntax error : identifier 'MyException'	d:\Local\sa3qApp.cpp	1041	
Error	5	error C2310: catch handlers must specify one type	d:\Local\sa3qApp.cpp	1041	 
Error	6	error C2065: 'StreamWriter' : undeclared identifier	d:\Local\sa3qApp.cpp	1043	 
Error	7	error C2065: 'pwriter' : undeclared identifier	d:\Local\sa3qApp.cpp	1043	 
Error	8	error C2061: syntax error : identifier 'StreamWriter'	d:\Local\sa3qApp.cpp	1043	 
Error	9	error C3921: Use of S-prefixed strings requires /clr:oldSyntax command line option	d:\Local\sa3qApp.cpp	1043	 
Error	10	fatal error C1903: unable to recover from previous error(s); stopping compilation	d:\Local\sa3qApp.cpp	1043

Open in new window

0
 
js-profiCommented:
syntax error : identifier 'MyException'    means you didn't include the header for MyException.

'StreamWriter' : undeclared identifier    iis same issue
0
 
sa3qAuthor Commented:
what is the header of  MyException


and the stram writer
0
 
js-profiCommented:
MyException is a private class where you should have a myexcept.h. If you don't have such a class or header you need to throw another class, e. g. std::string.

The stream writer also must be a known class. It is not standard c++. Use std::stringstream if you copied the code from somewhere elese as a substitute for streamwriter.
0
 
sa3qAuthor Commented:
please i don't want to go  far  from my question

i know  that their web services  and data base services  that run  in the start of the computer


i want my program  to  run  befor any user log to  his account in the log in  on  the start of the windows

how can i make like that
0
 
3_SCommented:
Ok forget the logging then,
Can you just explain what your program must do a the startup of your computer?
Maybe you are just trying to get the logged in user, but no one is logged in yet.
0
 
jazzIIIloveCommented:
please put your executing/the code that works as service into a while loop...while(true)

See what happens.

Best regards.
0
 
sa3qAuthor Commented:
my program must run  befor any user login to  his account because the  application  i will  put it on  the server to  make some services in the local network  to  the  users  on the lan

can  any body  help me  how to  run it  ??
0
 
3_SCommented:
Service.Create("d:\\Program Files\\MYapp\\start.exe", "sa3qApp", "sa3qApp", SERVICE_WIN32_OWN_PROCESS, true, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, "", "", nil, "", "");

If we look at your command (from the manual)
AllowDesktopInteraction
(boolean) Whether to allow the service process to interact with the desktop. If set to true, the service must run in the "LocalSystem" account. This can be done by setting the ServiceStartName to "LocalSystem".
This is set true in your command, has the localsystem account all the right there are needed to run?
0
 
sa3qAuthor Commented:
yes i run the program on  administrator  user
0
 
3_SCommented:
Since your is program is supposed to runs when no desktop is yet loaded is would recommend to set it to false.
The program has no GUI?
The last two parameters of the command are User and password. This is not set, so now it runs under the localsystem account
So to set to run with administrator user (adjust accordinaly)
Service.Create("d:\\Program Files\\MYapp\\start.exe", "sa3qApp", "sa3qApp", SERVICE_WIN32_OWN_PROCESS, false, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, "", "", nil, "yourdomain\\administrator", "yourpassword");
0
 
sa3qAuthor Commented:
3_S:  

i make that but the same problem  appear it   appear to me

error 1053  the service not response for starting in the exact time
0
 
sa3qAuthor Commented:
the application like  a server   their  is no  GUI
0
 
js-profiCommented:
did you implement the status callback function?
0
 
sa3qAuthor Commented:
>js-profi:
>did you implement the status callback function?

no???????
0
 
js-profiCommented:
each service has to implement a service_main function which could be compared to main of a console app. moreover, a service needs to supply a service_ctrl callback function which asynchronously responds to status requests of the SCM service control manager. See sample code.

// 
   // Service_Ctrl -   Where control signals from the Service Control Mgr
   //                  are handled.
   // 
   void WINAPI Service_Ctrl(DWORD dwCtrlCode)
   {
      DWORD dwState = SERVICE_RUNNING;

      switch(dwCtrlCode)
      {
         case SERVICE_CONTROL_STOP:
            dwState = SERVICE_STOP_PENDING;
            break;

         case SERVICE_CONTROL_SHUTDOWN:
            dwState = SERVICE_STOP_PENDING;
            break;

         case SERVICE_CONTROL_INTERROGATE:
            break;

         default:
            break;
      }

      // Set the status of the service.
      SetTheServiceStatus(dwState, NO_ERROR, 0, 0);
      OutputDebugString(
                 TEXT("SetTheServiceStatus, Service_Ctrl function\n"));

      // Tell service_main thread to stop.
      if ((dwCtrlCode == SERVICE_CONTROL_STOP) ||
                                 (dwCtrlCode == SERVICE_CONTROL_SHUTDOWN))
      {
         if (!SetEvent(hStopEvent))
            ErrorStopService(TEXT("SetEvent"));
         else
            OutputDebugString(TEXT("Signal service_main thread\n"));
      }
   }

   // 
   // ThreadProc -   Thread procedure for all three worker threads.
   // 
   DWORD WINAPI ThreadProc(LPVOID lpParameter)
   {
      INT nThreadNum = (INT)lpParameter;
      TCHAR szOutput[25];

      while(WaitForSingleObject(hStopEvent, 1000) != WAIT_OBJECT_0)
      {
      // Just to have something to do, it will beep every second.
         Sleep(1000);
         wsprintf(szOutput,TEXT("\nThread %d says Beep\n"),nThreadNum);
         OutputDebugString(szOutput); //Send visual to debugger.
      }

      return 0;
   }


   // 
   //  SetTheServiceStatus -   This just wraps up SetServiceStatus.
   // 
   void SetTheServiceStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode,
                            DWORD dwCheckPoint,   DWORD dwWaitHint)
   {
      SERVICE_STATUS ss;  // Current status of the service.

      // 
      // Disable control requests until the service is started.
      // 
      if (dwCurrentState == SERVICE_START_PENDING)
         ss.dwControlsAccepted = 0;
      else
         ss.dwControlsAccepted =
                       SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_SHUTDOWN;
                       // Other flags include SERVICE_ACCEPT_PAUSE_CONTINUE
                       // and SERVICE_ACCEPT_SHUTDOWN.

      // Initialize ss structure.
      ss.dwServiceType             = SERVICE_WIN32_OWN_PROCESS;
      ss.dwServiceSpecificExitCode = 0;
      ss.dwCurrentState            = dwCurrentState;
      ss.dwWin32ExitCode           = dwWin32ExitCode;
      ss.dwCheckPoint              = dwCheckPoint;
      ss.dwWaitHint                = dwWaitHint;

      // Send status of the service to the Service Controller.
      if (!SetServiceStatus(ssh, &ss))
         ErrorStopService(TEXT("SetServiceStatus"));
   }

   // 
   //  ErrorStopService -  Use this when there is an API error or bad
   //                      situation this just ends the service and
   //                      displays an error message to the debugger.
   // 
   void ErrorStopService(LPTSTR lpszAPI)
   {
      INT t;
      TCHAR   buffer[256]  = TEXT("");
      TCHAR   error[1024]  = TEXT("");
      LPVOID lpvMessageBuffer;
      DWORD  dwWaitRes;

      wsprintf(buffer,TEXT("API = %s, "), lpszAPI);
      lstrcat(error, buffer);

      ZeroMemory(buffer, sizeof(buffer));
      wsprintf(buffer,TEXT("error code = %d, "), GetLastError());
      lstrcat(error, buffer);

      // Obtain the error string.
      FormatMessage(
                FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
                NULL, GetLastError(),
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                (LPTSTR)&lpvMessageBuffer, 0, NULL);

      ZeroMemory((LPVOID)buffer, (DWORD)sizeof(buffer));
      wsprintf(buffer,TEXT("message = %s"), (TCHAR *)lpvMessageBuffer);
      lstrcat(error, buffer);

      // Free the buffer allocated by the system.
      LocalFree(lpvMessageBuffer);

      // Write the error string to the debugger.
      OutputDebugString(error);

      // If you have threads running, tell them to stop. Something went
      // wrong, and you need to stop them so you can inform the SCM.
      SetEvent(hStopEvent);

      // Wait for the threads to stop.
      for (t=1;TRUE;t++)
      {
         if ((dwWaitRes = WaitForMultipleObjects(3,hThreads,TRUE,1000))
                                                          == WAIT_OBJECT_0)
            break;
         else if ((dwWaitRes== WAIT_FAILED)||(dwWaitRes== WAIT_ABANDONED))
            break; // Our wait failed
         else
         {
            SetTheServiceStatus(SERVICE_STOP_PENDING, 0, t, 3000);
         }
      }

      // Stop the service.
      SetTheServiceStatus(SERVICE_STOPPED, GetLastError(), 0, 0);

   }

Open in new window

0
 
js-profiCommented:
To get the service status to 'started' your service_main should set the service status to running after initialization like

    SetTheServiceStatus(SERVICE_RUNNING, 0, 0, 0);

where SetTheServiceStatus is a function like
0
 
js-profiCommented:
see code SetTheServiceStatus
your service_main should set the service status to running after initialization like

    SetTheServiceStatus(SERVICE_RUNNING, 0, 0, 0);
   // 
   //  SetTheServiceStatus -   This just wraps up SetServiceStatus.
   // 
   void SetTheServiceStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode,
                            DWORD dwCheckPoint,   DWORD dwWaitHint)
   {
      SERVICE_STATUS ss;  // Current status of the service.

      // 
      // Disable control requests until the service is started.
      // 
      if (dwCurrentState == SERVICE_START_PENDING)
         ss.dwControlsAccepted = 0;
      else
         ss.dwControlsAccepted =
                       SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_SHUTDOWN;
                       // Other flags include SERVICE_ACCEPT_PAUSE_CONTINUE
                       // and SERVICE_ACCEPT_SHUTDOWN.

      // Initialize ss structure.
      ss.dwServiceType             = SERVICE_WIN32_OWN_PROCESS;
      ss.dwServiceSpecificExitCode = 0;
      ss.dwCurrentState            = dwCurrentState;
      ss.dwWin32ExitCode           = dwWin32ExitCode;
      ss.dwCheckPoint              = dwCheckPoint;
      ss.dwWaitHint                = dwWaitHint;

      // Send status of the service to the Service Controller.
      if (!SetServiceStatus(ssh, &ss))
         ErrorStopService(TEXT("SetServiceStatus"));
   }

Open in new window

0
 
sa3qAuthor Commented:
js-profi:

thank you  for  your attention

now i know that the problem  from my code  and i must code  service main

but if you can help  me  i attached the  main  code  it have  2 threads   each  one call  function  have  infinte loop  it  listener    how can  i use my code with  your code ???

please don't histate if you can help
int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{

	 CWinThread* thread1 =AfxBeginThread(N_mang,NULL,THREAD_PRIORITY_NORMAL,0,0,NULL);
	 CWinThread* thread2 =AfxBeginThread(S_Data,NULL,THREAD_PRIORITY_NORMAL,0,0,NULL);

	 HANDLE h[] = {thread1->m_hThread,thread2->m_hThread};
			for (int i = 0; i < 2; i++) {
			WaitForMultipleObjects(2, h, FALSE, INFINITE);
			}
		

  return 0;
}

Open in new window

0
 
js-profiCommented:
if your current app was started as service you already have some service_main which was calling WinMain. I know there are wrappers which make any win32 app a service. i assume you've used such a wrapper? or how did you get your app started as a service?

if i am right you only need to set the service status to running. do it in the WinMain after creating the threads but before waiting. use the SetTheServiceStatus function i copied from MSDN samples. you can get more docs and sample code searching for SCM or service.c in MSDN.
0
 
sa3qAuthor Commented:
js-profi:
i try to use all  the  code you type   but their ten's of  errors in compile

please can you give me  full  code  include your code with  my code  

/////////////////////////////
//on the above of the  code i add the functions  you make
///////////////////////////////
int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{

         CWinThread* thread1 =AfxBeginThread(N_mang,NULL,THREAD_PRIORITY_NORMAL,0,0,NULL);
         CWinThread* thread2 =AfxBeginThread(S_Data,NULL,THREAD_PRIORITY_NORMAL,0,0,NULL);

 SetTheServiceStatus(SERVICE_RUNNING, 0, 0, 0);

         HANDLE h[] = {thread1->m_hThread,thread2->m_hThread};
                        for (int i = 0; i < 2; i++) {
                        WaitForMultipleObjects(2, h, FALSE, INFINITE);
                        }
                

  return 0;
}

/////////////////////////////
and the  error
///////////////////////////////


Error	3	error C2065: 'SERVICE_RUNNING' : undeclared identifier
Error	4	error C2065: 'SERVICE_CONTROL_STOP' : undeclared identifier	
Error	5	error C2051: case expression not constant	
Error	6	error C2065: 'SERVICE_STOP_PENDING' : undeclared identifier	
Error	7	error C2065: 'SERVICE_CONTROL_SHUTDOWN' : undeclared identifier
Error	8	error C2051: case expression not constant	
Error	9	error C2065: 'SERVICE_STOP_PENDING' : undeclared identifier	
Error	10	error C2065: 'SERVICE_CONTROL_INTERROGATE' : undeclared identifier	
Error	11	error C2051: case expression not constant	
Warning	12	warning C4065: switch statement contains 'default' but no 'case' labels
Error	13	error C3861: 'SetTheServiceStatus': identifier not found
Error	14	error C2065: 'SERVICE_CONTROL_STOP' : undeclared identifier
Error	15	error C2065: 'SERVICE_CONTROL_SHUTDOWN' : undeclared identifier
Error	16	error C2065: 'hStopEvent' : undeclared identifier
Error	17	error C3861: 'ErrorStopService': identifier not found
Error	18	error C2065: 'hStopEvent' : undeclared identifier	
Error	19	fatal error C1903: unable to recover from previous error(s); stopping compilation

Open in new window

0
 
js-profiCommented:
have asked some questions. did you use a wrapper which makes your app a service?

most the errors should vanish after including windows.h. did you use stdafx.h? if yes you might have to add #include <winsvc.h> into stdafx.h.

can't help with code if i have not all information and full posting of your code.
0
 
sa3qAuthor Commented:
ok thank  you the service run  but it didn't run on the windows login  


i mean befor any user  logon

what is the problem ??
0
 
sa3qAuthor Commented:
the program  running in the logon  but  it not interactive  with  any thing  
0
 
js-profiCommented:
you mean logon or boot? services - which you can watch in the services applet - were always started before first login. it depends on their account whether they have access to local network or not. if started with local system account they have no access to network. better create a user specially for that service and start the service using that account. then it should be able to do something. loggings should be made to file cause desktop is not available .
0
 
sa3qAuthor Commented:
yes i  mean  boot

i choose local network  

i want to  run the program in winlogon.
The  program  run  perfect when  i use any  user desktop  and the administrator account run  the application  when  i log of the program  not closed but it  make like pause  and if i login  to  other account  it  resume  the session of the application i want the program  to  run without pause

may i have your  advise  
0
 
js-profiCommented:
i still have doubts whether your prog is a service. if you start it from desktop with admin rights it is not a service. a service can be installed once using an installer or have a own installing option, e. g. like invoking it by myservice -i. then the SCM (service control manager) applet form can be used to start/stop the service which keeps installed and it always runs at boot time before any login. after login you need process-to-process (P2P) communication to speek with the service or send jobs/request to it. P2P can be made based on sockets, shared memory, pipes, files, windows messages. if user logs out the service would still run.
0
 
js-profiCommented:
if you want to start your prog after login, you could use the 'at' tool which can be easily configured using the explorer at windows\tasks folder.
0
 
sa3qAuthor Commented:
please understand me  the program  installed as service and i make it to  start  automaticly
and it start automatic
the program  work  with  files and local  network and interactive with windows
it must be run  all  times
 i means  by all times
 1- when any user work on his desktop
 2- when  their is no  users logon to  his  account
this computer will  not be shut down and the service(program) must run  in the  winlogon screen
 thank you for your attention
0
 
sa3qAuthor Commented:
thank you

you solve the problem that appear to run the service

i will open new question because i want my program to be active if there is no user login to his account
0
 
js-profiCommented:
yes a service would all do what you request beside of interacting with the login screen. here a secured gina.dll would block any interference for login not being spied out by malware.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 17
  • 13
  • 5
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now