Help.Implementar un .exe como servicio

Help.Implementar un .exe como servicio

Postby thefull » Wed Nov 17, 2010 5:04 pm

Buenas.
He estado buscando por el foro, y no he encontrado nada que me resulte de utilidad.
Vi algunos post, pero parece que no funcionan en Windows XP o posteriores.

La idea es crear un servicio, que permita ser, start / pause / stop,
y que esté pueda crear hilos para determinadas tareas.

Por mucho que busco, no encuentro nada.
Si alguien puede iluminarme, eternamente tendrá mi agradeciendo. ;-)
Saludos
Rafa Carmona ( rafa.thefullARROBAgmail.com___quitalineas__)
User avatar
thefull
 
Posts: 731
Joined: Fri Oct 07, 2005 7:42 am
Location: Barcelona

Re: Help.Implementar un .exe como servicio

Postby Lautaro » Wed Nov 17, 2010 11:00 pm

Hola,

Revisa harbour puro y duro , alli puedes crear servicios para windows.


Saludos,

Lautaro Moreira
User avatar
Lautaro
 
Posts: 322
Joined: Fri Oct 07, 2005 2:44 pm
Location: Osorno, Chile

Re: Help.Implementar un .exe como servicio

Postby Daniel Garcia-Gil » Thu Nov 18, 2010 3:39 am

Rafa...


Puede que esto te sirva http://www.devx.com/cplus/Article/9857/0/page/1

intente implementarlo pero no he tenido exito, a ver si por alli van los tiros
Code: Select all  Expand view

function Main()
   MyService()
return nil


#pragma BEGINDUMP
#include <windows.h>
#include <hbapi.h>
#include <hbapifs.h>

#define SLEEP_TIME 5000
#define LOGFILE "memstatus.txt"

SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hStatus;
void ServiceMain(int argc, char** argv);
void ControlHandler(DWORD request);
void MyService( void );
 
LPSTR LToStr( long w )
{
   static char dbl[ HB_MAX_DOUBLE_LENGTH ];
   sprintf( dbl, "%f", ( double ) w );
   * strchr( dbl, '.' ) = 0;
   
   return ( char * ) dbl;
}    
 
int WriteToLog(char* str)
{
    HB_FHANDLE log; 
  LPSTR crlf = "\n";
    
    if( hb_fsFile( LOGFILE ) )
       log = hb_fsOpen(LOGFILE, FO_WRITE);
    else
       log = hb_fsCreate(LOGFILE, FO_WRITE);

    if (! log )
        return -1;
 
  hb_fsSeek( log, 0, FS_END );
    hb_fsWrite( log, str, strlen( str ) );
    hb_fsWrite( log, crlf, strlen( crlf ) );

    hb_fsClose(log);
   
    return 0;
}

// Service initialization
int InitService( void )
{
    int result;
    result = WriteToLog("Monitoring started." );
    return result ;
}


HB_FUNC( MYSERVICE )
{
   MyService();
}



void MyService( void )
{
    SERVICE_TABLE_ENTRY ServiceTable[2];
    ServiceTable[0].lpServiceName = "MemoryStatus";
    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);
}


void ServiceMain(int argc, char** argv)
{
    int error, result;
    MEMORYSTATUS memory;
    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(
        "MemoryStatus",
        (LPHANDLER_FUNCTION)ControlHandler);
    if (hStatus == (SERVICE_STATUS_HANDLE)0)
    {
        // Registering Control Handler failed
        return;
    }  
    // Initialize Service
   
    error = InitService();
    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)
    {
        char buffer[16];
        GlobalMemoryStatus(&memory);
        sprintf(buffer, "%d", memory.dwAvailPhys);
        result = WriteToLog(buffer);
        if (result)
        {
            ServiceStatus.dwCurrentState       = SERVICE_STOPPED;
            ServiceStatus.dwWin32ExitCode      = -1;
            SetServiceStatus(hStatus, &ServiceStatus);
            return;
        }

        Sleep(SLEEP_TIME);
    }
    return;
}


// Control handler function
void ControlHandler(DWORD request)
{
    switch(request)
    {
        case SERVICE_CONTROL_STOP:
             WriteToLog("Monitoring stopped.");

            ServiceStatus.dwWin32ExitCode = 0;
            ServiceStatus.dwCurrentState  = SERVICE_STOPPED;
            SetServiceStatus (hStatus, &ServiceStatus);
            return;
 
        case SERVICE_CONTROL_SHUTDOWN:
            WriteToLog("Monitoring stopped.");

            ServiceStatus.dwWin32ExitCode = 0;
            ServiceStatus.dwCurrentState  = SERVICE_STOPPED;
            SetServiceStatus (hStatus, &ServiceStatus);
            return;
       
        default:
            break;
    }
 
    // Report current status
    SetServiceStatus (hStatus,  &ServiceStatus);
 
    return;
}


#pragma ENDDUMP
 
User avatar
Daniel Garcia-Gil
 
Posts: 2365
Joined: Wed Nov 02, 2005 11:46 pm
Location: Isla de Margarita

Re: Help.Implementar un .exe como servicio

Postby Daniel Garcia-Gil » Thu Nov 18, 2010 3:45 am

Rafa...

Esta este ejemplo de harbour, pero tengo los mismos resultados que el post anterior
los fuentes de las wrapper estan en hbwin\win_svc.c

Code: Select all  Expand view

/*
 * $Id: testsvc.prg 15174 2010-07-25 08:45:50Z vszakats $
 */


/*
 * Harbour Project source code:
 * Windows Service API test code
 *
 * Copyright 2010 Jose Luis Capel - <jlcapel at hotmail . com>
 * www - http://harbour-project.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this software; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307 USA (or visit the web site http://www.gnu.org/).
 *
 * As a special exception, the Harbour Project gives permission for
 * additional uses of the text contained in its release of Harbour.
 *
 * The exception is that, if you link the Harbour libraries with other
 * files to produce an executable, this does not by itself cause the
 * resulting executable to be covered by the GNU General Public License.
 * Your use of that executable is in no way restricted on account of
 * linking the Harbour library code into it.
 *
 * This exception does not however invalidate any other reasons why
 * the executable file might be covered by the GNU General Public License.
 *
 * This exception applies only to the code released by the Harbour
 * Project under the name Harbour.  If you copy code from other
 * Harbour Project or Free Software Foundation releases into a copy of
 * Harbour, as the General Public License permits, the exception does
 * not apply to the code that you add in this way.  To avoid misleading
 * anyone as to the status of such modified files, you must delete
 * this exception notice from them.
 *
 * If you write modifications of your own for Harbour, it is your choice
 * whether to permit this exception to apply to your modifications.
 * If you do not wish that, delete this exception notice.
 *
 */


#include "hbwin.ch"

#include "common.ch"

#define _SERVICE_NAME "Harbour_Test_Service"

PROCEDURE Main( cMode )

   DEFAULT cMode TO "S" /* NOTE: Must be the default action */

   SWITCH Upper( cMode )
   CASE "I"

      IF win_serviceInstall( _SERVICE_NAME, "Harbour Windows Test Service" )
         ? "Service has been successfully installed"
      ELSE
         ? "Error installing service: " + hb_ntos( wapi_GetLastError() )
      ENDIf
      EXIT

   CASE "U"

      IF win_serviceDelete( _SERVICE_NAME )
         ? "Service has been deleted"
      ELSE
         ? "Error deleting service: " + hb_ntos( wapi_GetLastError() )
      ENDIf
      EXIT

   CASE "S"

      IF win_serviceStart( _SERVICE_NAME, "SrvMain" )
         ? "Service has started OK"
      ELSE
         ? "Service has had some problems: " + hb_ntos( wapi_GetLastError() )
      ENDIF
      EXIT

   ENDSWITCH

   RETURN

#include "fileio.ch"

PROCEDURE SrvMain()
   LOCAL n := 0
   LOCAL fhnd := hb_FCreate( hb_dirBase() + "testsvc.out", FC_NORMAL, FO_DENYNONE + FO_WRITE )
   LOCAL cParam

   FWrite( fhnd, "Startup" + hb_eol() )

   FOR EACH cParam IN hb_AParams()
      FWrite( fhnd, "Parameter " + hb_ntos( cParam:__enumIndex() ) + " >" + cParam + "<" + hb_eol() )
   NEXT

   DO WHILE win_serviceGetStatus() == WIN_SERVICE_RUNNING
      FWrite( fhnd, "Work in progress " + hb_ntos( ++n ) + hb_eol() )
      hb_idleSleep( 0.5 )
   ENDDO

   FWrite( fhnd, "Exiting..." + hb_eol() )
   FClose( fhnd )

   win_serviceSetExitCode( 0 )
   win_serviceStop()

   RETURN

 
User avatar
Daniel Garcia-Gil
 
Posts: 2365
Joined: Wed Nov 02, 2005 11:46 pm
Location: Isla de Margarita

Re: Help.Implementar un .exe como servicio

Postby thefull » Thu Nov 18, 2010 11:26 am

Muchas gracias!
Estaba mirando sobre xHarbour y no veía nada.
Saludos
Rafa Carmona ( rafa.thefullARROBAgmail.com___quitalineas__)
User avatar
thefull
 
Posts: 731
Joined: Fri Oct 07, 2005 7:42 am
Location: Barcelona

Re: Help.Implementar un .exe como servicio

Postby thefull » Fri Nov 19, 2010 9:26 am

Daniel, ¿ que problemas has encontrado ? Lo que he encontrado a sido principalmente con Windows 7 , que por mucho que sea un usuario con
derecho de Administrador, no le daba la gana de arrancar el servicio.
Además, he jugado con él y lo he adaptado para hacer una pausa, y todo correcto.
Saludos
Rafa Carmona ( rafa.thefullARROBAgmail.com___quitalineas__)
User avatar
thefull
 
Posts: 731
Joined: Fri Oct 07, 2005 7:42 am
Location: Barcelona

Re: Help.Implementar un .exe como servicio

Postby Daniel Garcia-Gil » Fri Nov 19, 2010 11:57 am

Rafa

uso window 7, me lanza error 1063
lo ejecuto desde virtual pc con el mismo resultado
User avatar
Daniel Garcia-Gil
 
Posts: 2365
Joined: Wed Nov 02, 2005 11:46 pm
Location: Isla de Margarita

Re: Help.Implementar un .exe como servicio

Postby thefull » Fri Nov 19, 2010 3:05 pm

y si ejecutas;
c:\>runas /user:Administrador "testsvc.exe i"

¿ Te instala el servicio ?
Saludos
Rafa Carmona ( rafa.thefullARROBAgmail.com___quitalineas__)
User avatar
thefull
 
Posts: 731
Joined: Fri Oct 07, 2005 7:42 am
Location: Barcelona

Re: Help.Implementar un .exe como servicio

Postby thefull » Fri Nov 19, 2010 3:08 pm

Daniel Garcia-Gil wrote:Rafa

uso window 7, me lanza error 1063
lo ejecuto desde virtual pc con el mismo resultado


Por cierto, NO USAR -mt , no funciona con threads!
Me he puesto con J.L.Capel, y me lo ha comunicado, y comenta que desde Harbour no le han dado una solución.
Lástima, me hubiese gustado hacer además algo con threads, pero menos da una piedra.
Saludos
Rafa Carmona ( rafa.thefullARROBAgmail.com___quitalineas__)
User avatar
thefull
 
Posts: 731
Joined: Fri Oct 07, 2005 7:42 am
Location: Barcelona

Re: Help.Implementar un .exe como servicio

Postby Daniel Garcia-Gil » Fri Nov 19, 2010 3:13 pm

Rafa


Perfecto, me faltaba el parametro para que instalace el servicio :oops: (que descuido)
User avatar
Daniel Garcia-Gil
 
Posts: 2365
Joined: Wed Nov 02, 2005 11:46 pm
Location: Isla de Margarita


Return to FiveWin para Harbour/xHarbour

Who is online

Users browsing this forum: Google [Bot] and 27 guests