如何将Windows控制台程序转换为Windows服务程序? [英] How to convert a windows console program to a windows service program?

查看:74
本文介绍了如何将Windows控制台程序转换为Windows服务程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的VC ++中,我完成了编写Windows控制台的代码。但现在,我必须将其转换为Windows服务代码。



所以我更改了控制台程序中的一些代码,如下所示



In my VC++, I completed to write a code of windows console. But now, I must convert it to a windows service code.

So I have changed some code in that console program like as follows

#include <winsvc.h>

int main()
{
    SERVICE_TABLE_ENTRY ste[] = {
       {_T("TEST Win"}, (LPSERVICE_MAIN_FUNCTION) MyTestWindows},
    };

    StartServiceCtrlDisplatcher(ste);

    return 0;
}



in MyTestWindows(),我编码如下。




and in MyTestWindows(), I coded as follows.

void MyTestWindows()
{
    g_hSrv = RegisterServiceCtrlHandler(_T("TestWin"),
                        LPHANDLER_FUNCTION)MyServiceHandler);
    if (g_hSrv == 0) return;

    MyServiceSet(SERVICE_START_PENDING);
    g_bPause = FALSE;

    g_ExitEvent = CreateEvent(NULL, TRUE, FALSE, _T("TESTWINSTATUS");

    MyServiceSet(SERVICE_RUNNING);

    // This is same of windows console program...

    MyServiceSet(SERVICE_STOPPED);
    return;
}





但是当我运行这个程序时,没有线程或Windows服务正在运行。它是无声的......?
请告诉我这个编码和解决方案的错误。



提前谢谢。



我尝试了什么:



这个问题浪费了2天。



But when I run this program, No thread or windows service are running. It's silent ....?
Please let me know what is my fault of this coding and solution.

Thank you in advance.

What I have tried:

More 2 days wasted for this problem.

推荐答案

您没有向我们展示工作线程创建和功能以及 MyServiceSet MyServiceHandler 实现。所以我们找不到问题这些函数中的ms。



You did not show us the worker thread creation and function and the MyServiceSet and MyServiceHandler implementations. So we can't locate problems within those function.

MyServiceSet(SERVICE_RUNNING);
 
// This is same of windows console program...
 
MyServiceSet(SERVICE_STOPPED);

服务通常在那里创建一个线程:

A service usually creates a thread there instead:

MyServiceSet(SERVICE_RUNNING);
HANDLE hThread = CreateThread (NULL, 0, ServiceWorkerThread, NULL, 0, NULL);
WaitForSingleObject(hThread, INFINITE);
MyServiceSet(SERVICE_STOPPED);

DWORD WINAPI ServiceWorkerThread(LPVOID lpParam)
{
    while (WaitForSingleObject(g_ExitEvent, SOME_TIMEOUT) != WAIT_OBJECT_0)
    {
        // Code from your console program
    }
    return 0;
}

g_ExitEvent 必须由 MyServiceHandler 设置 SERVICE_CONTROL_STOP



最后,为了确定:你安装了服务吗?

g_ExitEvent has to be set by the MyServiceHandler upon SERVICE_CONTROL_STOP.

Finally, just to be sure: Have you installed your service?


这篇关于如何将Windows控制台程序转换为Windows服务程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆