Hi,

The clock synchronization program below needs to be amended to add another clocksync.ini option to allow the progam to run just once and then terminate. Request you to please give your inputs for this.

Thanks,
Marconi.

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

#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0400
#include <windows.h>
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "service.h"
#include "p2_msgs.h"
#include "save.h"
#define SOCKETZ_CODE
#include "socketz.h"
#ifdef _CONSOLE
#include "err_log.inc"
#endif


#define window_x_size 400
#define small_window_x_size 320
#define window_y_size 200
#define timer_interval 1000

#define WSA_CONNECT (WM_USER + 1)
#define WSA_READ        (WM_USER + 2)



HANDLE                    instance_handle,
                    main_handle,
                    thread_handle;
char                    SZSERVICENAME[] = {"ClockSync"},
                    SZSERVICEDISPLAYNAME[] = {"Clock Synchronisation Service"},
                    version_string[30],
                    window_title[100],
                    ip_address[20],
                    ini_file_name[] = {"ClockSync.ini"},
                    sync_request[] = {"{001G0D}"};
int                    ip_port,
                               sleep_time,
                          timer_gap;
struct sockaddr_in    local_sin,
        dest_sin;
SOCKET        sock;
BOOL        is_connected,
        is_terminating,
        testing,
        trust_if_unsynced,
        is_rugby,
        only_log_updates,
        done_update;


void clock_sync_process(HANDLE);

void fatal_error(char*);

LRESULT WINAPI main_proc(HWND,
                       UINT,
                  WPARAM,
                  LPARAM);

void clock_sync_thread(void);

void init_system(void);

void get_file_version(void);


#ifdef _CONSOLE

void ServiceStart(DWORD argc,
              LPTSTR *argv)

{

    if (!ReportStatusToSCMgr(SERVICE_START_PENDING,
                   NO_ERROR,
                  10000)) 
       return;

       clock_sync_process(GetModuleHandle(NULL));

}

#else

WINAPI WinMain(HINSTANCE    instance,
             HINSTANCE    prev_instance,
             LPSTR    cmd_line,
             int        show_cmd)


{

    clock_sync_process(instance);
    return(0);

}
#endif



void clock_sync_process(HANDLE hInst)
{

    WNDCLASS    wndclass;
    MSG        msg;
    char        small_screen = GetSystemMetrics(SM_CXSCREEN) < 800;
    WSADATA        wsa_data;
    BOOL        bRet;


    save_executable_location(SZSERVICENAME);
    set_language();
    get_file_version();

    if (WSAStartup(MAKEWORD(2,
                     0),
               &wsa_data)) 
        fatal_error(msgs[err_35]);

    instance_handle = hInst;
    memset(&wndclass,
                 0,
                 sizeof(WNDCLASS));
    wndclass.style = CS_HREDRAW | CS_VREDRAW;
    wndclass.hInstance = hInst;
    wndclass.hCursor = LoadCursor(NULL,
                            IDC_ARROW);
    wndclass.hbrBackground = GetStockObject(WHITE_BRUSH);
    wndclass.lpszClassName = SZSERVICENAME;
    wndclass.lpfnWndProc = main_proc;
    RegisterClass(&wndclass);

    main_handle = CreateWindow(SZSERVICENAME,
                         window_title,
                         WS_OVERLAPPEDWINDOW,
                         0,
                         0,
                         0,
                         0,
                         NULL,
                         NULL,
                         hInst,
                         NULL);

    if (!SetTimer(main_handle,
            1,
            timer_interval,
            NULL)) 
    {
        MessageBox(NULL,
               msgs[err_34],
               "",
               MB_ICONEXCLAMATION | MB_OK);
        return;
    }

    while( (bRet = GetMessage(&msg,
                    NULL,
                    0,
                    0)) != 0)
    { 
        if (-1 == bRet)
        {
            fatal_error("Unknown error occurred");
        }
        else
        {
            TranslateMessage(&msg); 
            DispatchMessage(&msg); 
        }
    }

    KillTimer(main_handle,
              1);

    WSACleanup();

}




void ServiceStop(void)
{
    is_terminating = TRUE;
}





void fatal_error(char  *message)

{

#ifndef _CONSOLE
    log_a_fatal_error(message);
    MessageBox(0,
           message,
           msgs[literal_143],
           MB_OK);
#else
    event_log_write(SZSERVICEDISPLAYNAME,
                version_string,
                message,
                EVENTLOG_ERROR_TYPE,
                0,
                0,
                NULL);
    
#endif

    PostQuitMessage(0);

}




LRESULT WINAPI main_proc(HWND      hwnd,
                  UINT        message,
                  WPARAM  w_param,
                  LPARAM    l_param)

{


    int         cnt;
    char         buffer[1000];
    SYSTEMTIME   st,
              lt;


    switch (message)
    {

        
        case WM_CREATE:
#ifdef _CONSOLE
        ReportStatusToSCMgr(SERVICE_RUNNING,
                    NO_ERROR,
                 0);
#endif

        init_system();
        thread_handle = CreateThread(NULL,
                              0,
                              (LPTHREAD_START_ROUTINE) clock_sync_thread,
                              NULL,
                              0,
                              &cnt);
            break;

        case WM_TIMER:
            if (is_terminating)
            {
                PostQuitMessage(0);
                return 0;
            }

            if (is_connected && (--timer_gap == 0))
                is_connected = FALSE;

            break;

        case WM_CLOSE:
            is_terminating = TRUE;
            closesocket(sock);
            break;

        case WSA_CONNECT:
            if (!WSAGETSELECTERROR(l_param)) 
            {
                send(sock,
                     sync_request,
                     strlen(sync_request),
                     0);
                is_connected = TRUE;
            }
            break;


        case WSA_READ:
            memset(buffer,
                   0,
                   sizeof(buffer));
            if (cnt = recv(sock,
                    buffer,
                    sizeof(buffer),
                    0))
            {
                OutputDebugString(buffer);

                GetLocalTime(<);
                is_rugby = TRUE;

                if ( (is_rugby = ('1' == buffer[16])) ||
                     (is_rugby = ('3' == buffer[16])) ||
                     (is_rugby = ('5' == buffer[16])) ||
                     (is_rugby = ('7' == buffer[16])) ||
                     (is_rugby = ('9' == buffer[16])) ||
                     (is_rugby = ('B' == buffer[16])) ||
                     (is_rugby = ('D' == buffer[16])) ||
                     (is_rugby = ('F' == buffer[16])) ||
                     trust_if_unsynced )
                {
                    memset(&st,
                           0,
                           sizeof(SYSTEMTIME));

                    buffer[37] = 0;
                    st.wYear = atoi(buffer + 33);

                    buffer[32] = 0;
                    st.wMonth = atoi(buffer + 30);
                    
                    buffer[30] = 0;
                    st.wDay = atoi(buffer + 27);

                    buffer[26] = 0;
                    st.wSecond = atoi(buffer + 24);

                    buffer[23] = 0;
                    st.wMinute = atoi(buffer + 21);

                    buffer[20] = 0;
                    st.wHour = atoi(buffer + 18);

                    if ( (lt.wSecond != st.wSecond) ||
                         (lt.wMinute != st.wMinute) ||
                         (lt.wHour   != st.wHour) ||
                         (lt.wDay    != st.wDay) ||
                         (lt.wMonth  != st.wMonth) ||
                         (lt.wYear   != st.wYear) )
                    {
                        done_update = TRUE;

                        if (!testing)
                            SetLocalTime(&st);

                        wsprintf(buffer,
                                     "Clock updated from %.2i:%.2i:%.2i %.2i/%.2i/%.4i to %.2i:%.2i:%.2i %.2i/%.2i/%.4i %s\n",
                                       lt.wHour,
                            lt.wMinute,
                            lt.wSecond,
                            lt.wDay,
                            lt.wMonth,
                            lt.wYear,
                            st.wHour,
                            st.wMinute,
                            st.wSecond,
                            st.wDay,
                            st.wMonth,
                            st.wYear,
                            is_rugby ? "" : "(Unsynced)" );
                    }
                    else
                    {
                        done_update = FALSE;
                        wsprintf(buffer,
                                     "%s",
                                     "Clock not updated - no difference found\n");
                    }
                    printf(buffer);
                    OutputDebugString(buffer);

                    if (done_update || !only_log_updates)
                        event_log_write(SZSERVICEDISPLAYNAME,
                        version_string,
                        buffer,
                        EVENTLOG_INFORMATION_TYPE,
                        0,
                        0,
                        NULL);
                }
                else
                {
                    wsprintf(buffer + 100,
                                 "%.2i:%.2i:%.2i %.2i/%.2i/%.4i  Unsynced time received from server - %s\n",
                                 lt.wHour,
                                 lt.wMinute,
                                 lt.wSecond,
                                 lt.wDay,
                                 lt.wMonth,
                                 lt.wYear,
                                 buffer);
                    printf(buffer + 100);
                    OutputDebugString(buffer + 100);
                }
                timer_gap = sleep_time;
            }

            closesocket(sock);
            break;
    }

    return(DefWindowProc(hwnd,
             message,
             w_param,
             l_param));
}



void clock_sync_thread(void)
{

    char            mess[100];
    unsigned long    var = 1;
    BOOL            just_connect = FALSE;
    int            err;

    
    while (1)
    {
        if (is_terminating)
            return;

        if (!is_connected)
        {
            if (!just_connect)
            {
                    if (INVALID_SOCKET == (sock = socket(AF_INET,
                                        SOCK_STREAM,
                            0)) )
                {
                    wsprintf(mess,
                                 msgs[err_45],
                                 "socket");
                    fatal_error(mess);
                }

                set_address(0,
                      0,
                      0,
                      &local_sin);

                if (bind(sock,
                           (struct sockaddr *) &local_sin,
                           sizeof(local_sin)) == SOCKET_ERROR)

                {
                    closesocket(sock);
                }

                set_address(ip_address,
                      (unsigned short) ip_port,
                      0,
                      &dest_sin);
                ioctlsocket(sock,
                    FIONBIO,
                    &var);

                WSAAsyncSelect(sock,
                             main_handle,
                             WSA_READ,
                              FD_READ | FD_CLOSE);
            }

            if ( (connect(sock,
                  (PSOCKADDR) &dest_sin,
                  sizeof(dest_sin)) == SOCKET_ERROR) &&
                 ((err = WSAGetLastError()) != WSAEISCONN) ) 
            {
                if (WSAECONNREFUSED == err)
                    Sleep(rand());
                else
                {
                    just_connect = TRUE;
                    Sleep(1000);
                }
            }
            else
            {
                is_connected = TRUE;
                send(sock,
                                    sync_request,
                        strlen(sync_request),
                        0);
                just_connect = FALSE;
            }
        }
        else 
            Sleep(1000);

    }

}




void init_system(void)
{

    char    buffer[20];
    int       cnt;


    GetPrivateProfileString("ClockSync",
              "ip address", 
              "165.45.45.113",
              buffer,
              sizeof(buffer),
              ini_file_name);

    ip_port = GetPrivateProfileInt("ClockSync",
                        "ip port",
                        3000,
                        ini_file_name);

    sleep_time = GetPrivateProfileInt("ClockSync",
                  "sleep",
                  100,
                  ini_file_name);

    testing = GetPrivateProfileInt("ClockSync",
                       "testing",
                       0,
                       ini_file_name);

    trust_if_unsynced = GetPrivateProfileInt("ClockSync",
                           "trust unsynced times",
                           0,
                           ini_file_name);
    only_log_updates = GetPrivateProfileInt("ClockSync",
                          "only log updates",
                          1,
                          ini_file_name);

    cnt = inet_addr(buffer);
    memcpy(ip_address,
                             &cnt,
                             4);

    timer_gap = -1;

    is_connected = FALSE;

    srand((unsigned int)time(NULL));

}




void get_file_version(void)
{
    
    VS_FIXEDFILEINFO      *vfi;
    int                              leng;
    char                           buff2[200],
                                     buffer[200];


    GetModuleFileName(NULL,
                                 buff2,
                                 sizeof(buff2));
    GetFileVersionInfo(buff2,
                                0,
                                sizeof(buffer),
                                buffer);

    leng = 200;

    VerQueryValue(buffer,
                           "\\",
                           &vfi,
                           &leng);
    
    wsprintf(version_string,
                "v%i.%i.%i.%i",
                vfi->dwProductVersionMS >> 16,
                (vfi->dwProductVersionMS) & 0xffff,
                vfi->dwProductVersionLS >> 16,
    (vfi->dwProductVersionLS) & 0xffff);

    wsprintf(window_title,
                "%s %s",
    SZSERVICEDISPLAYNAME,
                version_string);
               
}

Is this all your own work?

If it is, why is it suddenly so difficult for you to add reading a .ini file?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.