我有一个用 Microsoft Visual C++ 用 C 语言编写的旧程序,我需要实现某种“keepalive”,所以我能够将它认为进程间通信接收到一个新程序中,如果它会杀死并重新启动第一个程序过去 5 秒内未收到任何消息。
问题是我一直在寻找任何 C 语言的 IPC for Windows 教程或示例,但我找到的几乎所有内容都是针对 C++ 的。
任何帮助或资源?
编辑:正如@Adriano 在答案中建议的那样,我正在尝试使用共享内存。但是由于某种我无法捕捉到的异常,Windows 正在终止启动程序。调用 CopyMemory 时发生。
代码如下:
#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;
int launchMyProcess();
void killMyProcess();
bool checkIfMyProcessIsAlive();
STARTUPINFO sInfo;
PROCESS_INFORMATION pInfo;
HANDLE mappedFile;
LPVOID pSharedMemory;
long lastReceivedBeatTimeStamp;
const int MSECONDS_WITHOUT_BEAT = 500;
const LPTSTR lpCommandLine = "MyProcess.exe configuration.txt";
int main(int argc, char* argv[])
{
mappedFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(int), "Global\\ActivityMonitor");
LPVOID pSharedMemory = MapViewOfFile(mappedFile, FILE_MAP_READ, 0, 0, sizeof(int));
if(!launchMyProcess()){
cout<<"Error creating MyProcess.exe"<<endl;
UnmapViewOfFile(pSharedMemory);
CloseHandle(mappedFile);
return -1;
}
while(true){
Sleep(100);
if(!checkIfMyProcessIsAlive()){
cout<<"Relaunching MyProcess...";
killMyProcess();
if(!launchMyProcess()){
cout<<"Error relaunching MyProcess.exe"<<endl;
UnmapViewOfFile(pSharedMemory);
CloseHandle(mappedFile);
return -1;
}
}
}
UnmapViewOfFile(pSharedMemory);
CloseHandle(mappedFile);
return 0;
}
bool checkIfMyProcessIsAlive()
{
static int volatile latestMagicNumber = 0;
int currentMagicNumber = 0;
CopyMemory(¤tMagicNumber, pSharedMemory, sizeof(int));
if(currentMagicNumber != latestMagicNumber){
latestMagicNumber = currentMagicNumber;
return true;
}
return false;
}
int launchMyProcess()
{
ZeroMemory(&sInfo, sizeof(sInfo));
sInfo.cb = sizeof(sInfo);
ZeroMemory(&pInfo, sizeof(pInfo));
return CreateProcess(NULL, lpCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &sInfo, &pInfo);
}
void killMyProcess()
{
TerminateProcess(pInfo.hProcess, 0);
CloseHandle(pInfo.hProcess);
CloseHandle(pInfo.hThread);
Sleep(3000);
}