《完美C/C++》之windows守护进程

#include 
#include 
#include 
#include 
#include 
LPCTSTR szAppClassName  = TEXT("Print Service");
LPCTSTR szAppWindowName = TEXT("Print Service");
using namespace std;

//隐藏DOS黑窗口
#pragma comment(linker,"/subsystem:\"windows\"  /entry:\"mainCRTStartup\"" )

//定义路径最大程度
#define MAX_PATH_NUM 4096
//定义守护进程名称
#define PROCCESS_NAME "printServer.exe"
//定义写入的注册表路径
#define SELFSTART_REGEDIT_PATH "Software\\Microsoft\\Windows\\CurrentVersion\\Run\\"

//设置本身开机自启动
BOOL SetSelfStart()
{
    //获取程序完整名称
    char pName[MAX_PATH_NUM]={0};
    GetModuleFileNameA(NULL,pName,MAX_PATH_NUM);

    //在注册表中写入启动信息
    HKEY hKey=NULL;
    LONG lRet=0;
    lRet=RegOpenKeyExA(HKEY_CURRENT_USER,SELFSTART_REGEDIT_PATH,0,KEY_ALL_ACCESS,&hKey);

    //判断是否成功
    if(lRet!=ERROR_SUCCESS)
    {
        return FALSE;
    }

    lRet=RegSetValueExA(hKey,"testProtect",0,REG_SZ,(const unsigned char*)pName,strlen(pName)+sizeof(char));

    //判断是否成功
    if(lRet!=ERROR_SUCCESS)
    {
        return FALSE;
    }

    //关闭注册表
    RegCloseKey(hKey);
    return TRUE;
}

int main()
{
    //获得守护的进程的句柄
    HWND handle = FindWindow(NULL, szAppWindowName);
    if (handle != NULL)
    {
        MessageBox(NULL, TEXT("Application is already running"), szAppClassName, MB_ICONERROR);
        ExitProcess(1);
    }

    //设置程序开机自启动
    if(!SetSelfStart())
    {
        cout<<"守护进程开机自启动失败"<return -1;
    }

    STARTUPINFOA si;
    //进程对象
    PROCESS_INFORMATION pi;
    //初始化
    ZeroMemory(&si,sizeof(si));
    si.cb=sizeof(si);
    ZeroMemory(&pi,sizeof(pi));

    //获取当前程序的路径
    char pPath[MAX_PATH_NUM]={0};
    GetCurrentDirectoryA(MAX_PATH_NUM,pPath);

    //拼接需要守护的程序
    strcat(pPath,"\\");
    strcat(pPath,PROCCESS_NAME);

    //构造cmd执行守护进程的字符串
    char pCmd[MAX_PATH_NUM]={0};
    //strcat(pCmd,"cmd /c ");
    strcat(pCmd,pPath);

    //无限循环,监视守护进程
    do{
        //检查守护程序是否存在
        if(_access(pPath,0)!=-1)
        {
            //创建子进程,判断是否执行成功
            if(!CreateProcessA(NULL,pCmd,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
            {
                cout<<"守护进程启动失败,程序即将退出"<return -1;
            }

            //启动成功,获取进程的ID
            cout<<"守护进程成功,ID:"<//无限等待子进程退出
            WaitForSingleObject(pi.hProcess,INFINITE);
            //如果退出了
            cout<<"守护进程退出了。。。"<//关闭进程和句柄
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
        }
        else
        {
            cout<<"守护程序不存在"<//睡一下,重启
        Sleep(1000);
    }
    while(true);
    return 0;
}

你可能感兴趣的:(windows,c++)