最近在折腾我的EeePC, 装的xp系统,100G硬盘,没有显示器,是我的专用下载机。 另外一台台式机是Ubuntu。 想要写个Windows Service常驻在EeePC后台,然后就可以从Ubuntu或我的手机上控制它了。 初步期望有以下功能:
1. 可以启动或关闭指定程序,主要是emule和BT。可以关机。
2. 可以监视eMule和BT的下载目录,有下载完成的文件就move到台式机上,因为小机器100G硬盘不够用,几部高清就满了。
3. 可以从指定位置copy种子文件,并开启BT下载。
其实或许有现成软件可以凑合,比如ts客户端(手机和Ubuntu都有对应软件),虽然做不到100%方便。 但出于练习网络及多线程编程的目的还是决定自己实现一个,服务端用c,客户端用python。 今天找了点windows服务的资料,翻了翻MSDN,先弄了个服务壳子出来:
#include <windows.h>
#include <stdio.h>
#define RECV_BUFF_SIZE 1024
#define LOGFILE "C:\\Workspace\\ServiceLog.txt"
#define MAX_LISTEN 5
#define S_NAME "Downlad Service By Crane"
SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hStatus;
void ServiceMain(int argc, char **argv);
void ControlHandler(DWORD request);
int WriteToLog(char *str){
FILE* log = NULL;
log = fopen(LOGFILE, "a+");
if (log == NULL){
return -1;
}
fprintf(log, "%s\n", str);
fclose(log);
return 0;
}
int main(void){
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = S_NAME;
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;
int result = StartServiceCtrlDispatcher(ServiceTable);
return 0;
}
void ServiceMain(int argc, char **argv){
int error = 0;
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(
S_NAME,
(LPHANDLER_FUNCTION)ControlHandler);
if(hStatus == ((SERVICE_STATUS_HANDLE)0)){
return;
}
error = WriteToLog("Download service started.");
if(error){
ServiceStatus.dwCurrentState =
SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = -1;
SetServiceStatus(hStatus,&ServiceStatus);
return;
}
ServiceStatus.dwCurrentState =
SERVICE_RUNNING;
SetServiceStatus(hStatus, &ServiceStatus);
while (ServiceStatus.dwCurrentState ==
SERVICE_RUNNING ){
if(WriteToLog("Service run.")){
ServiceStatus.dwCurrentState =
SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = -1;
SetServiceStatus(hStatus, &ServiceStatus);
return;
}
Sleep(5000);
}
return;
}
void ControlHandler(DWORD request)
{
switch(request)
{
case SERVICE_CONTROL_STOP:
WriteToLog("Download service stopped.");
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
return;
case SERVICE_CONTROL_SHUTDOWN:
WriteToLog("Download service stopped.");
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
return;
default:
break;
}
// Report current status
SetServiceStatus (hStatus, &ServiceStatus);
return;
}
|
周末有时间把Socket通讯加上去,最后一步再做多线程处理。
阅读(1554) | 评论(1) | 转发(0) |