Hi, Waldemar

In my previous email, I got
-------------------------begin---------------------
Your mail to 'Python-win32' with the subject

    Re: [python-win32] Runnin Python app as service with separate
console

Is being held until the list moderator can review it for approval.

The reason it is being held:

    Message body is too big: 119956 bytes with a limit of 30 KB
-------------------------end---------------------

So I resend my previous email without big attachments again.


--------------------------previous email start-------------------

Thank you very much for your code.
I still have difficulties to run my python application as a service well.

What I am trying to do is something like :
C:\python23\python.exe my_server.py -3 --pid=pid.file --slog=log.file >run_log.file

When I open a DOS window, run the above command, no problem at all.
When I try to put it into a service, I got problem.

"install_3d_app_service.cpp" is a program to install sftc3win.exe(sftc_3d_app_service.cpp) into a Windows' service. Inside sftc_3d_app_service.cpp, it will spawn "python". After reboot the machine, no problem, everything works fine, please see attached picture python_running.JPG. The problem is that after I log off, the "python" has gone. Even if I log in as a non-administrative account, I log off, then the "python" has gone, even I am in the session of non-administrative account, I can not terminate(End Process)
the "python" process. I am totally confused by this.

I also can use Windows' Scheduled Tasks to add a task as "At System startup", I can run it as a service, but after I log in/log off any account, the "python" service has gone.

Can you or someone else point me a direction how to solve the problem?
Or I am in the wrong direction, I have to use the same way as you described ?

One thing I want to mention is that  my python scripts work at linux too,
and I want to keep it run at the DOS window for easier debugging.

I am using python2.3.

Best regards.
Michael Li


Waldemar Osuch wrote:
On 4/6/06, Michael Li <[EMAIL PROTECTED]> wrote:

> Although it is not obvious from Twisted documentation it is trivial to
> run an application as a windows service as long as you use *.tac files
> to build it.

Can you share your code ?

I also have an application using Twisted, but I got problems to run as a
service.


I am using py2exe with custom setup.py file.
Additionally I have startup.tac and winservice.py
 - startup.tac - if you know Twisted then you know what goes into
startup.tac :-).
 - winservice.py - is the stub file that gets compiled into
winservice.exe.  This is the file that you will register with Windows.
 winservice.exe -h will list all the options.  I do not remember them
at them moment.
 - setup.py - is almost standard setup file.  You run it with python
setup.py py2exe.  The trick is to list all required modules
explicitly.  I list all except the modules that hold my Twisted
application logic. The advantage is that I can replace the modules
without recompiling.  Only restart the service and the bug fix is
implemented.  Your admin will love you for that :-)
The only problem is if you missed a required module the service will
die silently when starting.  Luckily the Python traceback gets
recorded in Windows Application Log.
Check it to see what the service is complaining about, add the missing
part, rinse and repeat.

See the attached files for an example.
The original idea comes from:
http://twistedmatrix.com/trac/browser/sandbox/moonfallen/
See it for more documentation.


------------------------------------------------------------------------

import sys
import os

import win32serviceutil, win32service

basecf = "startup.tac"
cftype = "python"
svcname = "dispatcher"
display = "Twisted Task Dispatcher"
reactortype = "default"

class ServiceControl(win32serviceutil.ServiceFramework):

    _svc_name_ = svcname
    _svc_display_name_ = display

    def SvcDoRun(self):
        from twisted.application import app
        app.installReactor(reactortype)

        from twisted.internet import reactor
        from twisted.application import service
        from twisted.python import util, log, logfile

        # look for a readable config file
        for cf in (util.sibpath(sys.executable, basecf),
                   util.sibpath(__file__, basecf),
                   basecf):
            try:
                open(cf, 'r').close()
            except EnvironmentError:
                continue
            else:
                startdir = os.path.dirname(cf)
                os.chdir(startdir)
                sys.path.insert(0, startdir)
                break

        lf = logfile.LogFile('%s.log' %svcname, 'logs')
        log.startLogging(lf)
        log.msg("Loading application from %s" % cf)

        service_app = service.loadApplication(cf, cftype)
        app.startApplication(service_app , False)
        reactor.run(installSignalHandlers=0)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        from twisted.internet import reactor
        reactor.callFromThread(reactor.stop)


if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(ServiceControl)


------------------------------------------------------------------------

import sys

# without this section taskscheduler can not be found
import py2exe.mf as modulefinder
import win32com
for p in win32com.__path__[1:]:
    modulefinder.AddPackagePath('win32com', p)
for extra in ['win32com.taskscheduler']:
    __import__(extra)
    m = sys.modules[extra]
    for p in m.__path__[1:]:
        modulefinder.AddPackagePath(extra, p)

from distutils.core import setup
import py2exe


setup(service = ['winservice'],
        zipfile = "lib/library.zip",
        data_files = (('', ['startup.tac',
                            'config.ini',
                            'backend.py',
                            'dbloader.py',
                            'dispatcher.py',
                            'xlsparser.py',
                           ]),
                      ('wsdl', ['wsdl/MFISLoader.wsdl',]),
                      ('logs', []),
                  ),
        options = {'global': {'verbose': '0'},
                   'py2exe': {'optimize': 2,
                              'dist_dir': 'dispatcher',
                              'excludes': ['perfmon'],
                              'dll_excludes': [],
                              'packages': ['twisted.application',
                                           'twisted.python',
                                           'twisted.web',
                                           'elementtree',
                                           'pyExcelerator',
                                          ],
                              'includes': ['datetime',
                                           'pythoncom',
                                           'cElementTree',
                                           'cx_Oracle',
                                           'twisted.mail.smtp',
                                           'utils.batch',
                                           
'win32com.taskscheduler.taskscheduler',
                                           ],
                              }
                  },
        )

==========
This email message and any attachments are for the sole use of the intended 
recipients and may contain proprietary and/or confidential information which 
may be privileged or otherwise protected from disclosure. Any unauthorized 
review, use, disclosure or distribution is prohibited. If you are not the 
intended recipients, please contact the sender by reply email and destroy the 
original message and any copies of the message as well as any attachments to 
the original message.
#include <stdio.h>
#include <string.h>
#include <iostream.h>
#include <windows.h>
#include <winsvc.h>

#ifdef  __cplusplus
 #ifndef MESSAGEBOX
  #define MESSAGEBOX ::MessageBox
 #endif
#else
 #ifndef MESSAGEBOX
  #define MESSAGEBOX MessageBox
 #endif
#endif

#define SFTC_3D_APP_SERVICE_REG "Software\\SFTC\\DEFORM-3D\\5.1"
#define SFTC_3D_APP_SERVICE "sftc3win.exe"
#define SFTC_3D_APP_SERVICE_PATH_REG_STRING "AppService"

#define SFTC_3D_APP_SERVICE_NAME "DEFORM3DAppService"
#define SFTC_3D_APP_SERVICE_DISPLAY_NAME "DEFORM 3D Application Service"

int isFileExist(const char * szFileName);

int main(int argc, char* argv[])
{
    static char* szCaption = "DEFORM - ERROR";
    static char* szDebugCaption = "DEFORM - DEBUG";
    char  szBuffer[1024];
    char  szCommand[1024];

        HKEY  hKey;
        DWORD dwDisp, dwSize, dwType;
        char szPath[_MAX_PATH];

    int nRetCode = 0;
    int nShowDebugMessage = 0;
    int nLen = 0;
    int i = 0;

    int nGetPathFromCommand = 0;
    char szPathFromCommand[1024];
    char szCurrentFolder[_MAX_PATH];

    SC_HANDLE Deform3dAppService,scm;
    
    for(i=0; i<argc; i++)
    {
        if ( !_strcmpi(argv[i], "-help" ) ||
             !_strcmpi(argv[i], "-h") ||
             !_strcmpi(argv[i], "/?") )
        {
            printf("\nUsage : %s [-d] [-h] [-path]\n\n", argv[0]);

            exit(0);
        }
    }

/*
 * Debug flag
 */
    nShowDebugMessage = 0;
    for(i=0; i<argc; i++)
    {
        if ( !_strcmpi(argv[i], "-d" ) )
        {
            nShowDebugMessage = 1;
            break;
        }
    }

/* get path */
    nGetPathFromCommand = 0;
    strcpy(szPathFromCommand, "");
    for(i=0; i<argc; i++)
    {
        if ( !_strcmpi(argv[i], "-path" ) )
        {
            nGetPathFromCommand = 1;

            if ( argv[i+1] )
            {
                nRetCode = sscanf(argv[i+1], "%s", szPathFromCommand);
                if ( nRetCode != 1 )
                {
                    printf("\nPlease specify a full absolute path of 3d 
application server.\n");
                    exit(-1);
                }
            } else
            {
                printf("\nPlease specify a full absolute path 3d application 
server.\n");
                exit(-2);
            }
            break;
        }
    }

    if ( nShowDebugMessage && nGetPathFromCommand )
    {
        sprintf(szBuffer, "The path you specified is : %s", szPathFromCommand);
        
        MESSAGEBOX(NULL, szBuffer, szDebugCaption, MB_OK  | MB_TOPMOST);
    }
   
    strcpy(szCurrentFolder, "");
    nRetCode = GetCurrentDirectory(_MAX_PATH, szCurrentFolder);
    if ( nRetCode == 0 )
    {
        printf("\nCan not get the current folder, exit.\n");
        exit(-3);
    } else
    {
        if ( nShowDebugMessage )
        {
            sprintf(szBuffer, "The current folder is : %s", szCurrentFolder);
        
            MESSAGEBOX(NULL, szBuffer, szDebugCaption, MB_OK  | MB_TOPMOST);
        }
    }

        scm=OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);

    if(!scm)
    {
        strcpy(szBuffer, "Can not open Windows service control manager, 
exit.\n\n");
        
        MESSAGEBOX(NULL, szBuffer, szCaption, MB_OK | MB_ICONSTOP | MB_TOPMOST);
                
        return 1;
    }

    nRetCode = RegCreateKeyEx( 
        HKEY_LOCAL_MACHINE, 
        SFTC_3D_APP_SERVICE_REG, 
        0, 0, REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE,
        0, &hKey, &dwDisp ) ;
    if ( nRetCode == ERROR_SUCCESS )
    {
        nRetCode = RegQueryValueEx(hKey, 
            SFTC_3D_APP_SERVICE_PATH_REG_STRING, 
            NULL, &dwType,(LPBYTE)(szPath),&dwSize);
        if ( nRetCode != ERROR_SUCCESS )
        {
            strcpy(szPath, szCurrentFolder);
            /*
            strcpy(szBuffer, "The executable path of DEFORM 3D application 
service not found, exit.\n\n");
            strcat(szBuffer, "Please specify a path to DEFORM 3D application 
service and run from DOS window.\n");
        
            MESSAGEBOX(NULL, szBuffer, szCaption, MB_OK | MB_ICONSTOP | 
MB_TOPMOST);
        
            return 2;
            */
        }    
    } else
    {
        strcpy(szPath, szCurrentFolder);
        /*
        strcpy(szBuffer, "The registry of DEFORM 3D application service not 
found, exit.\n\n");
        strcat(szBuffer, "Please specify a path to DEFORM 3D application 
service and run from DOS window.\n");
        
        MESSAGEBOX(NULL, szBuffer, szCaption, MB_OK | MB_ICONSTOP | MB_TOPMOST);
        
        return 3;
        */
    }

    if ( nGetPathFromCommand )
    {
        strcpy(szCommand, szPathFromCommand);
    } else
    {
        strcpy(szCommand, szPath);
    }
    
    nLen = strlen(szCommand);
    if ( nLen > 0 )
    {
        if ( szCommand[nLen-1] != '\\' )
        {
            szCommand[nLen] = '\\';
            szCommand[nLen+1] = '\0';
        }
    }
    strcat(szCommand, SFTC_3D_APP_SERVICE);
  
    if ( nShowDebugMessage )
    {
        sprintf(szBuffer, "The service prgram is : %s", szCommand);
        
        MESSAGEBOX(NULL, szBuffer, szDebugCaption, MB_OK | MB_TOPMOST);
    }

    nRetCode = isFileExist((const char *)szCommand);
    if ( !nRetCode )
    {
        strcpy(szBuffer, "The DEFORM 3D application service program not found, 
exit.\n\n");
        
        MESSAGEBOX(NULL, szBuffer, szCaption, MB_OK | MB_ICONSTOP | MB_TOPMOST);
        
        return 4;
    }
    
        Deform3dAppService=CreateService(scm,
        SFTC_3D_APP_SERVICE_NAME,
                SFTC_3D_APP_SERVICE_DISPLAY_NAME,
                SERVICE_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS 
|SERVICE_INTERACTIVE_PROCESS ,SERVICE_AUTO_START,
                SERVICE_ERROR_NORMAL,
                szCommand, /* "C:\\Michael\\tmp\\Debug\\TempService.exe", */
                0,0,0,0,0);
        if(!Deform3dAppService)
        {
                CloseServiceHandle(scm);
        strcpy(szBuffer, "Can not create Windows service, exit.\n\n");
        
        MESSAGEBOX(NULL, szBuffer, szCaption, MB_OK | MB_ICONSTOP | MB_TOPMOST);
        
                return 5;
        }
        CloseServiceHandle(Deform3dAppService);
        CloseServiceHandle(scm);
        
    return 0;
}

int isFileExist(const char * szFileName)
{
     FILE * f;

     if ( !szFileName )
     {
         return 0;
     }

     f=fopen(szFileName, "r");

     if (f==NULL)
     {
         return 0;
     } else
     {
         fclose(f);
         return 1;
     }
}

==========
This email message and any attachments are for the sole use of the intended 
recipients and may contain proprietary and/or confidential information which 
may be privileged or otherwise protected from disclosure. Any unauthorized 
review, use, disclosure or distribution is prohibited. If you are not the 
intended recipients, please contact the sender by reply email and destroy the 
original message and any copies of the message as well as any attachments to 
the original message.

==========
This email message and any attachments are for the sole use of the intended 
recipients and may contain proprietary and/or confidential information which 
may be privileged or otherwise protected from disclosure. Any unauthorized 
review, use, disclosure or distribution is prohibited. If you are not the 
intended recipients, please contact the sender by reply email and destroy the 
original message and any copies of the message as well as any attachments to 
the original message.
/******************************************************************************
 *
 * $Id: sftc_3d_app_service.cpp,v 1.1 2004/06/04 21:28:28 mli Exp $
 *
 * Copyright (C) Scientific Forming Technologies Corp.
 * All rights reserved.
 *
 * Author : Michael Li
 * Date   : May 28, 2004
 *
 * Start/Stop DEFORM 3D application server service
 *
 ******************************************************************************/

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <direct.h>
#include <time.h>
#include <process.h>
#include <windows.h>
#include <winsvc.h>

#ifdef  __cplusplus
 #ifndef MESSAGEBOX
  #define MESSAGEBOX ::MessageBox
 #endif
#else
 #ifndef MESSAGEBOX
  #define MESSAGEBOX MessageBox
 #endif
#endif

void ServiceMain(DWORD argc, LPTSTR *argv); 
void ServiceCtrlHandler(DWORD nControlCode);
BOOL UpdateServiceStatus(
    DWORD dwCurrentState, DWORD dwWin32ExitCode,
        DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint,
        DWORD dwWaitHint);
BOOL StartServiceThread();
DWORD ServiceExecutionThread(LPDWORD param);
HANDLE hServiceThread;
void KillService();

char *strServiceName = "DEFORM3DAppService";
SERVICE_STATUS_HANDLE nServiceStatusHandle; 
HANDLE killServiceEvent = NULL;
BOOL nServiceRunning = FALSE;
DWORD nServiceCurrentStatus = 0;
HANDLE h3DAppService = NULL;

//#define RUN_SFTC_3D_APP_SERVICE "run3apse.exe"
#define RUN_SFTC_3D_APP_SERVICE "def_as.bat"

#define SFTC_SERVER_PID_FILE 
"COM\\server_queue_fem\\config\\sftc_3d_win_app_server.pid"
#define SFTC_SERVER_LOG_FILE 
"COM\\server_queue_fem\\log\\server_running_log.txt"
#define SFTC_SERVER_STARTING_LOG_FILE 
"COM\\server_queue_fem\\log\\server_starting_log.txt"
#define SFTC_SERVER_START_FILE 
"COM\\server_queue_fem\\bin\\sftc_3d_win_app_server.bat"
#define SFTC_SERVER_PYTHON_FILE "COM\\server_queue_fem\\kernel\\sftc_server.py"
#define SFTC_SERVER_PYTHON_COMMAND "PYTHON\\python.exe"
#define SFTC_SERVER_START_FOLDER "COM\\server_queue_fem\\bin"
#define SFTC_100PERCENT_SYMBOL "%"

char  szStartingFolder[1024];

int isFileExist(const char * szFileName);
int deleteFile(const char* pszFileName);

void main(int argc, char* argv[])
{
    static char* szDebugCaption = "DEFORM - DEBUG";
    char* lpMark=NULL;
    int nRetCode = 0;
    int nShowDebugMessage = 0;
    int i = 0;
    int nLen = 0;

    char szBuffer[1024];
    char szCurrentFolder[_MAX_PATH];

        SERVICE_TABLE_ENTRY servicetable[]=
        {
                {strServiceName,(LPSERVICE_MAIN_FUNCTION)ServiceMain},
                {NULL,NULL}
        };
        BOOL success = FALSE;

#if 0 // 0 comment out
    char  szCommand[1024];
    char  szFullPidFile[1024];
    char  szFullLogFile[1024];
    char  szFullStartingLogFile[1024];
    char  szFullStartFile[1024];
    char  szFullPythonFile[1024];
    char  szFullPythonCommand[1024];
    char  szFullStartFolder[1024];
#endif // 0 comment out

    
    for(i=0; i<argc; i++)
    {
        if ( !_strcmpi(argv[i], "-help" ) ||
             !_strcmpi(argv[i], "-h") ||
             !_strcmpi(argv[i], "/?") )
        {
            printf("\nUsage : %s [-d] [-h]\n\n", argv[0]);

            exit(0);
        }
    }

/*
 * Debug flag
 */
    nShowDebugMessage = 0;
    for(i=0; i<argc; i++)
    {
        if ( !_strcmpi(argv[i], "-d" ) )
        {
            nShowDebugMessage = 1;
            break;
        }
    }

    strcpy(szStartingFolder, argv[0]);

    /* find startup directory */
    if ((lpMark=strrchr(szStartingFolder, '\\')) != NULL)
                 * (lpMark + 1)='\0';
        else
                szStartingFolder[0]='\0';

    if ( nShowDebugMessage )
    {
        sprintf(szBuffer, "The starting folder is : %s", szStartingFolder);
        
        MESSAGEBOX(NULL, szBuffer, szDebugCaption, MB_OK  | MB_TOPMOST);
    }
    
    strcpy(szCurrentFolder, "");
    nRetCode = GetCurrentDirectory(_MAX_PATH, szCurrentFolder);
    if ( nRetCode == 0 )
    {
        printf("\nCan not get the current folder, exit.\n");
        exit(-1);
    } else
    {
        if ( nShowDebugMessage )
        {
            sprintf(szBuffer, "The current folder is : %s", szCurrentFolder);
        
            MESSAGEBOX(NULL, szBuffer, szDebugCaption, MB_OK  | MB_TOPMOST);
        }
    }

    if ( szStartingFolder[0] == '\0' )
    {
        strcpy(szStartingFolder, szCurrentFolder);
    }

#if 0 // 0 comment out
    strcpy(szFullPidFile, szStartingFolder);
    strcat(szFullPidFile, SFTC_SERVER_PID_FILE);

    strcpy(szFullLogFile, szStartingFolder);
    strcat(szFullLogFile, SFTC_SERVER_LOG_FILE);

    strcpy(szFullStartingLogFile, szStartingFolder);
    strcat(szFullStartingLogFile, SFTC_SERVER_STARTING_LOG_FILE);
#if 0 // debug purpose
    strcpy(szFullStartingLogFile, "C:\\Temp\\t.log");
#endif // debug purpose

    strcpy(szFullStartFile, szStartingFolder);
    strcat(szFullStartFile, SFTC_SERVER_START_FILE);

    strcpy(szFullPythonFile, szStartingFolder);
    strcat(szFullPythonFile, SFTC_SERVER_PYTHON_FILE);

    strcpy(szFullPythonCommand, szStartingFolder);
    strcat(szFullPythonCommand, SFTC_SERVER_PYTHON_COMMAND);

    strcpy(szFullStartFolder, szStartingFolder);
    //strcat(szFullStartFolder, SFTC_SERVER_START_FOLDER);
        
        sprintf(szCommand,"%s %s -3 --pid=%s --slog=%s > %s", 
            szFullPythonCommand, 
            szFullPythonFile,
            szFullPidFile,
            szFullStartingLogFile,
            szFullLogFile
        );    
#endif // 0 comment out

        success=StartServiceCtrlDispatcher(servicetable);
        if(!success)
        {
                //error occured
        }
}

void ServiceMain(DWORD argc, LPTSTR *argv)
{
        BOOL success;
        nServiceStatusHandle=RegisterServiceCtrlHandler(
        strServiceName,
                (LPHANDLER_FUNCTION)ServiceCtrlHandler);
        if(!nServiceStatusHandle)
        {
                return;
        }
        success=UpdateServiceStatus(
        SERVICE_START_PENDING,NO_ERROR,0,1,3000);
        if(!success)
        {
                return;
        }
        killServiceEvent=CreateEvent(0,TRUE,FALSE,0);
        if(killServiceEvent==NULL)
        {
                return;
        }
        success=UpdateServiceStatus(
        SERVICE_START_PENDING,NO_ERROR,0,2,1000);
        if(!success)
        {
                return;
        }
        success=StartServiceThread();
        if(!success)
        {
                return;
        }
        nServiceCurrentStatus=SERVICE_RUNNING;
        success=UpdateServiceStatus(SERVICE_RUNNING,NO_ERROR,0,0,0);
        if(!success)
        {
                return;
        }
        WaitForSingleObject(killServiceEvent,INFINITE);
        CloseHandle(killServiceEvent);
}



BOOL UpdateServiceStatus(
    DWORD dwCurrentState, DWORD dwWin32ExitCode,
        DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint,
        DWORD dwWaitHint)
{
        BOOL success;
        SERVICE_STATUS nServiceStatus;
        nServiceStatus.dwServiceType=SERVICE_WIN32_OWN_PROCESS;
        nServiceStatus.dwCurrentState=dwCurrentState;
        if(dwCurrentState==SERVICE_START_PENDING)
        {
                nServiceStatus.dwControlsAccepted=0;
        }
        else
        {
                nServiceStatus.dwControlsAccepted=SERVICE_ACCEPT_STOP           
        
                        |SERVICE_ACCEPT_SHUTDOWN;
        }
        if(dwServiceSpecificExitCode==0)
        {
                nServiceStatus.dwWin32ExitCode=dwWin32ExitCode;
        }
        else
        {
                nServiceStatus.dwWin32ExitCode=ERROR_SERVICE_SPECIFIC_ERROR;
        }
        nServiceStatus.dwServiceSpecificExitCode=
        dwServiceSpecificExitCode;
        nServiceStatus.dwCheckPoint=dwCheckPoint;
        nServiceStatus.dwWaitHint=dwWaitHint;

        success=SetServiceStatus(nServiceStatusHandle,&nServiceStatus);

        if(!success)
        {
                KillService();
                return success;
        }
        else
                return success;
}

BOOL StartServiceThread()
{
        DWORD id;
        hServiceThread=CreateThread(0,0,
                (LPTHREAD_START_ROUTINE)ServiceExecutionThread,
                0,0,&id);
        if(hServiceThread==0)
        {
                return false;
        }
        else
        {
                nServiceRunning=true;
                return true;
        }

}

DWORD ServiceExecutionThread(LPDWORD param)
{
    char  szCommand[1024];
    char  szFullPidFile[1024];
    char  szFullLogFile[1024];
    char  szFullStartingLogFile[1024];
    char  szFullStartFile[1024];
    char  szFullPythonFile[1024];
    char  szFullPythonCommand[1024];
    char  szFullStartFolder[1024];

        int nRetCode = 0;
        char* args[64];


        STARTUPINFO si;
        PROCESS_INFORMATION pi;
        ZeroMemory( &si, sizeof(si) );
        si.cb = sizeof(si);
        ZeroMemory( &pi, sizeof(pi) );

        memset(args, 0, 64*sizeof(char));
        h3DAppService = NULL;
    
    if ( szStartingFolder )
    {
        _chdir(szStartingFolder);
    }

    strcpy(szFullPidFile, szStartingFolder);
    strcat(szFullPidFile, SFTC_SERVER_PID_FILE);

    strcpy(szFullLogFile, szStartingFolder);
    strcat(szFullLogFile, SFTC_SERVER_LOG_FILE);

    strcpy(szFullStartingLogFile, szStartingFolder);
    strcat(szFullStartingLogFile, SFTC_SERVER_STARTING_LOG_FILE);
#if 0 // debug purpose
    strcpy(szFullStartingLogFile, "C:\\Temp\\t.log");
#endif // debug purpose

    strcpy(szFullStartFile, szStartingFolder);
    strcat(szFullStartFile, SFTC_SERVER_START_FILE);

    strcpy(szFullPythonFile, szStartingFolder);
    strcat(szFullPythonFile, SFTC_SERVER_PYTHON_FILE);

    strcpy(szFullPythonCommand, szStartingFolder);
    strcat(szFullPythonCommand, SFTC_SERVER_PYTHON_COMMAND);

    strcpy(szFullStartFolder, szStartingFolder);
    //strcat(szFullStartFolder, SFTC_SERVER_START_FOLDER);
    
    
        sprintf(szCommand,"%s %s -3 --pid=%s --slog=%s > %s", 
            szFullPythonCommand, 
            szFullPythonFile,
            szFullPidFile,
            szFullStartingLogFile,
            szFullLogFile
        );
        

        /* NG
        sprintf(szCommand,"%s %s -3 --pid=%s --slog=%s", 
            szFullPythonCommand, 
            szFullPythonFile,
            szFullPidFile,
            szFullStartingLogFile
            //szFullLogFile
        );
                */
        /* ok
        sprintf(szCommand,"\"%s\" %s -3", 
            szFullPythonCommand, 
            szFullPythonFile
            //szFullPidFile,
            //szFullStartingLogFile
            //szFullLogFile
        );
                */

        nRetCode = isFileExist(szFullPidFile);
        if ( nRetCode )
        {
                deleteFile(szFullPidFile);
        }

        nRetCode = isFileExist(szFullStartingLogFile);
        if ( nRetCode )
        {
                deleteFile(szFullStartingLogFile);
        }

        nRetCode = isFileExist(szFullLogFile);
        if ( nRetCode )
        {
                deleteFile(szFullLogFile);
        }

        // sprintf(szCommand,"%s", "cmd /K start 
C:\\DEFORM3D\\V6_0\\def_as.bat");
        // sprintf(szFullPythonCommand,"cmd /K  \"%s\"", szCommand);
        // semi ok sprintf(szCommand,"%s", "C:\\DEFORM3D\\V6_0\\def_as.bat");

        /* NG
        sprintf(szCommand,"cmd /C \"%s %s -3\"", 
            szFullPythonCommand, 
            szFullPythonFile
            //szFullPidFile,
            //szFullStartingLogFile
            //szFullLogFile
        );
                */
        /*
    sprintf(szCommand,"cmd /K start /WAIT \"%s\"", 
            szFullPythonCommand, 
            szFullPythonFile
            //szFullPidFile,
            //szFullStartingLogFile
            //szFullLogFile
        );
                */
        /*
        args[0] = szCommand;
        _spawnv(_P_NOWAIT, args[0], args);
        */

        /*
        system("C:\\DEFORM3D\\V6_0\\def_as.bat");
        return 0;
        */

        BOOL bSuccess = CreateProcess( 
        NULL,
#if 1 // 0 comment out
                szCommand,
                //szFullPythonCommand,
        //".\\PYTHON\\python.exe 
.\\COM\\server_queue_fem\\kernel\\sftc_server.py -3 
--pid=.\\COM\\server_queue_fem\\config\\sftc_3d_win_app_server.pid > 
.\\COM\\server_queue_fem\\log\\server_running_log.txt",
        //"C:\\Shared\\nightly_build\\V80_USB\\source\\app_server\\DEF_ARM.exe",
        //"C:\\Shared\\nightly_build\\V80_USB\\source\\app_server\\DEF_ARM.com",
#else // 0 comment
        RUN_SFTC_3D_APP_SERVICE,
#endif // 0 comment out
        NULL, 
        NULL,
                FALSE,
                DETACHED_PROCESS | CREATE_NO_WINDOW,
                /*
                TRUE,
                CREATE_NO_WINDOW,
                */
/*
        FALSE,  
        CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW, //0, 
*/
        //DETACHED_PROCESS,
        //CREATE_NEW_CONSOLE,
        NULL, 
        NULL, 
        &si, 
        &pi );


        if(bSuccess)
        {
                CloseHandle( pi.hThread );
                h3DAppService = pi.hProcess;
        }

        return 0;
}

void KillService()
{
        nServiceRunning=false;
        SetEvent(killServiceEvent);
        UpdateServiceStatus(SERVICE_STOPPED,NO_ERROR,0,0,0);
        
        if(h3DAppService)
        {
                TerminateProcess(h3DAppService, UINT(-1));
                h3DAppService = NULL;
        }
}

void ServiceCtrlHandler(DWORD nControlCode)
{
        BOOL success;
        switch(nControlCode)
        {       
        case SERVICE_CONTROL_SHUTDOWN:
        case SERVICE_CONTROL_STOP:
                nServiceCurrentStatus=SERVICE_STOP_PENDING;
                success=UpdateServiceStatus(
            SERVICE_STOP_PENDING,NO_ERROR,0,1,3000);
                KillService();          
                return;
        default:
                break;
        }
        UpdateServiceStatus(nServiceCurrentStatus,NO_ERROR,0,0,0);
}

int isFileExist(const char * szFileName)
{
     FILE * f;

     if ( !szFileName )
     {
         return 0;
     }

     f=fopen(szFileName, "r");

     if (f==NULL)
     {
         return 0;
     } else
     {
         fclose(f);
         return 1;
     }
}

int deleteFile(const char* pszFileName)
{
        unlink(pszFileName);

        return 0;
}

==========
This email message and any attachments are for the sole use of the intended 
recipients and may contain proprietary and/or confidential information which 
may be privileged or otherwise protected from disclosure. Any unauthorized 
review, use, disclosure or distribution is prohibited. If you are not the 
intended recipients, please contact the sender by reply email and destroy the 
original message and any copies of the message as well as any attachments to 
the original message.
_______________________________________________
Python-win32 mailing list
Python-win32@python.org
http://mail.python.org/mailman/listinfo/python-win32

Reply via email to