转载:
https://blog.csdn.net/kikaylee/article/details/51395360
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <io.h>
#include <iostream>
using namespace std;
#pragma comment(linker,"/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
#define MAX_PATH 4096
#define PROCCESS_NAME "test.exe"
#define SELFSTART_REGEDIT_PATH "Software\\Microsoft\\Windows\\CurrentVersion\\Run\\"
BOOL SetSelfStart()
{
char pName[MAX_PATH]={0};
GetModuleFileNameA(NULL,pName,MAX_PATH);
HKEY hKey=NULL;
LONG lRet=NULL;
lRet=RegOpenKeyExA(HKEY_LOCAL_MACHINE,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()
{
if(!SetSelfStart())
{
cout<<"守护进程开机自启动失败"<<endl;
return -1;
}
STARTUPINFOA si;
PROCESS_INFORMATION pi;
ZeroMemory(&si,sizeof(si));
si.cb=sizeof(si);
ZeroMemory(&pi,sizeof(pi));
char pPath[MAX_PATH]={0};
GetCurrentDirectoryA(MAX_PATH,pPath);
strcat(pPath,"\\");
strcat(pPath,PROCCESS_NAME);
char pCmd[MAX_PATH]={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<<"守护进程启动失败,程序即将退出"<<endl;
return -1;
}
cout<<"守护进程成功,ID:"<<pi.dwProcessId<<endl;
WaitForSingleObject(pi.hProcess,INFINITE);
cout<<"守护进程退出了。。。"<<endl;
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
else
{
cout<<"守护程序不存在"<<endl;
}
Sleep(2000);
}
while(true);
return 0;
}