首页 c语言编译win程序的五步(The five step of compiling win program in C language)

c语言编译win程序的五步(The five step of compiling win program in C language)

举报
开通vip

c语言编译win程序的五步(The five step of compiling win program in C language)c语言编译win程序的五步(The five step of compiling win program in C language) c语言编译win程序的五步(The five step of compiling win program in C language) Some time ago I wrote an article written by the form of service to achieve the purpose of some inspectionprograms article...

c语言编译win程序的五步(The five step of compiling win program in C language)
c语言编译win程序的五步(The five step of compiling win program in C language) c语言编译win程序的五步(The five step of compiling win program in C language) Some time ago I wrote an article written by the form of service to achieve the purpose of some inspectionprograms articles, as to how to write service I have introduced in the windows today, let's take a look at how to write the service program. Windows services are designed for applications that need to run in the background, and for tasks that do not interact with the user. In order to learn the basics of this console application, C (not C++) is the best choice. This article will establish and implement a simple service program that is designed to query the amount of physical memory available in the system, and then write the results to a text file. Finally, you can write your own Windows service using what you've learned. When I was writing my first NT service, I went to MSDN to look for examples. There I found an article written by Nigel Thompson: "Creating a Simple Win32 Service in C++". This article is accompanied by a C++ example. Although this article explains the service development process very well, I still feel the lack of important information I need. I want to understand what framework, what functions to call, and when to call, but C++ doesn't make me so relaxed about it. The object-oriented approach is convenient, but it is not conducive to learning the basic knowledge of the service program because it encapsulates the underlying Win32 function calls. That's why I think C is better suited for writing primary services or services for simple background tasks. After you have a thorough understanding of the service process, you can write it with C++. When I left my former job and had to transfer my knowledge to another person, it was very easy to explain the NT service by using the examples I wrote with C. A service is a console program that runs in the background and implements tasks that do not require user interaction. The Windows NT/2000/XP operating system provides specialized support for service programs. You can configure the installed Service program with the service control panel, which is the Windows 2000/XP control panel | management tools in the "service" (or "start" in the | "run" dialog box, enter the services.msc /s - Translator's note). You can configure the service to start automatically when the operating system starts, so you don't have to start the service manually each time you restart the system. This article will first explain how to create a service that periodically queries the available physical memory and writes the results to a text file. It then guides you through the entire process of generating, installing, and implementing services. The first step: the main function and global definition First, the required header files are included. The example calls the Win32 function (windows.h) and the disk file write (stdio.h): #include #include Next, two constants are defined: #define SLEEP_TIME 5000 #define LOGFILE "C:\\MyServices\\memstatus.txt"" SLEEP_TIME specifies the millisecond interval between two consecutive queries for available memory. Use the constant in the second step when you write the service cycle. LOGFILE defines the path to the log file, and you will use the WriteToLog function to export the results of the memory query to the file. The WriteToLog function is defined as follows: Int WriteToLog (char* STR) { FILE* log; Log = fopen (LOGFILE, a+); If (log = NULL) Return -1; Fprintf (log,%s\n, STR); Fclose (log); Return 0; } Several global variables are declared to share their values among multiple functions of the program. In addition, make a forward definition of function: SERVICE_STATUS ServiceStatus; SERVICE_STATUS_HANDLE hStatus; Void ServiceMain (int, argc, char**, argv); Void ControlHandler (DWORD request); Int, InitService (); Now that the preparations are in place, you can start coding. A subset of the service program console program. So, at first, you can define a main function, which is the entry point of the program. For service programs, the main code is surprisingly brief because it creates only the dispatch table and starts the control dispatcher. Void, main () { SERVICE_TABLE_ENTRY ServiceTable[2]; ServiceTable[0].lpServiceName = "MemoryStatus""; ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION) ServiceMain; ServiceTable[1].lpServiceName = NULL; ServiceTable[1]. LpServiceProc = NULL; Dispatch control machine / / thread start service StartServiceCtrlDispatcher (ServiceTable); } A program may contain several services. Each service must be listed in the special dispatch table (which defines an array of ServiceTable structures for this program). Each item in this table should be in the SERVICE_TABLE_ENTRY structure. It has two domains: LpServiceName: points to a pointer to the name string of the service; when the service is defined, the domain must be specified; LpServiceProc: refers to the pointer to the service principal function (service entry point); The last entry of the dispatch table must be the NULL name of the service name and the main function domain of the service. The text example program hosts only one service, so the definition of the service name is optional. SCM:Services Control Manager (service control manager) is a process that manages all the services in the system. When SCM starts a service, it waits for the main line of a process to call the StartServiceCtrlDispatcher function. Pass the dispatch table to StartServiceCtrlDispatcher. This converts the primary thread of the calling process to the control dispatcher. The dispatcher initiates a new thread that runs the ServiceMain function of each service in the dispatch table (there is only one service in the example of this article), and the dispatcher also monitors the execution of all services in the program. The dispatcher then passes control requests from the SCM to the service. Note: if the StartServiceCtrlDispatcher function is not called 30 seconds, will Baocuo, in order to avoid this situation, we must in the ServiceMain function (in the example) or non initializing service in a separate thread in the main function allocation table. The services described in this article do not need to guard against such a situation. After all the services in the allocation table have been executed (for example, the user stops them through the service control panel program) or when an error occurs. StartServiceCtrlDispatcher call returns. Then the main process terminates. The second step: ServiceMain function Listing 1 shows the code for ServiceMain. This function is the entry point of the service. It runs in a single thread, created by a control dispatcher. ServiceMain should register the control processor as early as possible for the service. This is done by calling the RegisterServiceCtrlHadler function. You pass the two parameter to this function: the service name and the pointer to the ControlHandlerfunction. It indicates that the control dispatcher calls the ControlHandler function to process the SCM control request. After registering the control processor, the status handle (hStatus) is obtained. By calling the SetServiceStatus function, the status of the service is reported to the SCM using hStatus. Listing 1 shows how to specify the service characteristics and their current state to initialize the ServiceStatus structure, and each domain of the ServiceStatus structure has its uses: DwServiceType: indicates the service type and creates the Win32 service. Assignment SERVICE_WIN32; DwCurrentState: Specifies the current state of the service. Because the initialization of the service has not been completed here, so the state here is SERVICE_START_PENDING; DwControlsAccepted: this domain tells the SCM service which domain to accept. The example in this article is to allow STOP and SHUTDOWN requests. The processing control request will be discussed in the third step; DwWin32ExitCode and dwServiceSpecificExitCode: these two domains are useful when you terminate the service and report exit details. When the service is initialized, they are not exited, so their value is 0; DwCheckPoint and dwWaitHint: these two domains represent more than 30 seconds when initializing a service process. The initialization of the example service is short in this article, so the values of these two fields are 0. Call the SetServiceStatus function to report the status of the service to the SCM. The hStatus handle and the ServiceStatus structure are provided. Note that ServiceStatus is a global variable, so you can use it across multiple functions. In the ServiceMain function, you assign values to several domains of the structure, which remain the same throughout the service's run, such as dwServiceType. After reporting the status of the service, you can call the InitService function to complete the initialization. This function simply adds an explanatory string to the log file. As shown in the following code: / / service initialization Int, InitService () { Int result; 结果:writetolog(“监测”。); 返回(结果); } 在中中,检查initservice函数的返回值。如果初始化有错(因为有 可能写日志文件失败)中,则将服务状态置为终止并退出: 误差= initservice(); 如果(错误) { / /初始化失败,终止服务 servicestatus.dwcurrentstate = service_stopped; servicestatus.dwwin32exitcode = - 1; SetServiceStatus(hStatus,及服务状态); / /退出中 返回; } 如果初始化成功,则向单片机报告状态: / /向单片机报告运行状态 servicestatus.dwcurrentstate = service_running; SetServiceStatus(hStatus,及服务状态); 接着,启动工作循环。每五秒钟查询一个可用物理内存并将结果写入日志文件。 如清单1所示,循环一直到服务的状态为service_running或日志文件写入出错为止。状态可能在controlhandler函数响应单片机控制请求时修改。 第三步:处理控制请求 在第二步中,你用中函数注册了控制处理器函数。控制处理器与处理各种Windows消息的窗口回调函数非常类似发送了什么请求并采取相应行动它检查单片机。 每次你调用SetServiceStatus函数的时候,必须指定服务接收停止和关机请求。清单2示范了如何在controlhandler函数中处理它们。 停止请求是单片机终止服务的时候发送的。例如,如果用户在”服务”控制面板中手动终止服务。关机请求是关闭机器时,由发送给所有运行中服务的请求两种情况的处理方式相同单片机: 写日志文件,监视停止; 向单片机报告service_stopped状态; 由于结构对于整个程序而言为全局量服务状态、服务状态中的工作循 环在当前状态改变或服务终止后停止其它的控制请求如:和继续在本文的例子没有处理停顿。 控制处理器函数必须报告服务状态,即便单片机每次发送控制请求的时候状态保持相同。因此,不管响应什么请求,都要调用SetServiceStatus。 第四步:安装和配置服务 程序编好了,将之编译成exe文件。本文例子创建的文件叫memorystatus。exe,将它拷贝到C:\服务文件夹。为了在机器上安装这个服务,需要用sc.exe可执行文件,它是Win32 SDK平台中附带的一个工具。(译者注:Visaul Studio .NET 2003 IDE环境中也有这个工具,具体存放位置在:C:\程序文件\微软Visual Studio .NET 2003 \的Common7 \工具\ bin WinNT)。使用这个实用工具可以安装和移除服务。其它控制操作将通过服务控制面板来完成以下是用命令行安装memorystatus服务的方法: SC创建memorystatus binpath = C:\服务\ memorystatus.exe 发出此创建命令。指定服务名和二进制文件的路径(注意binpath =和路径之间的那个空格)。安装成功后,便可以用服务控制面板来控制这个服务。用控制面板的工具栏启动和终止这个服务。 memorystatus的启动类型是手动,也就是说根据需要来启动这个服务。右键单击该服务,然后选择上下文菜单中的”属性”菜单项,此时显示该服务的属性窗口。在这里可以修改启动类型以及其它设置。你还可以从”常规”标签中启动/停止服务。以下是从系统中移除服务的方法: SC删除memorystatus 指定“删除”选项和服务名。此服务将被标记为删除,下次西通重启 后,该服务将被完全移除。 第五步:测试服务 从服务控制面板启动memorystatus服务。如果初始化不出错, 关于同志近三年现实表现材料材料类招标技术评分表图表与交易pdf视力表打印pdf用图表说话 pdf 示 启动成功。过一会儿将服务停止。检查一下C:\服务文件夹中 memstatus。 Service output for the TXT file. On my machine, the output is like this: Monitoring started. Two hundred and seventy-three million four hundred and sixty-nine thousand four hundred and forty Two hundred and seventy-three million three hundred and seventy-nine thousand three hundred and twenty-eight Two hundred and seventy-three million one hundred and thirty-three thousand five hundred and sixty-eight Two hundred and seventy-three million eighty-four thousand four hundred and sixteen Monitoring stopped. To test the behavior of MemoryStatus services in the event of an error, you can set the memstatus.txt file as read-only. As a result, the service should not start. Remove the read-only property, start the service, and set the file to read-only. The service will stop executing because the log file write failed at this time. If you update the contents of the service control panel, you will notice that the service status has been stopped. Yevgeny Menaker Translation: Northtibet
本文档为【c语言编译win程序的五步(The five step of compiling win program in C language)】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_731942
暂无简介~
格式:doc
大小:36KB
软件:Word
页数:11
分类:生活休闲
上传时间:2017-10-23
浏览量:18