Microsoft Visual C++ を使用して C で記述された古いプログラムがあり、ある種の「キープアライブ」を実装する必要があるため、新しいプログラムへのプロセス間通信を考えて受け取ることができます。過去 5 秒間にメッセージを受信していません。
問題は、私が C 言語で Windows 用の IPC のチュートリアルまたは例を探していたということですが、見つけたほとんどすべてが 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);
}