【发布时间】:2012-05-10 13:44:22
【问题描述】:
我有一个用 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);
}
【问题讨论】:
-
教程是否使用 C++ 并不重要,它们将使用相同的 C WIN32 函数。
-
没有,但是收到一个C教程会很高兴:)
-
so I am able to receive it thought interprocess communication into a new program有点模糊。您究竟是如何从旧程序中获取信息的?对我来说,这听起来不像是 IPC 问题。如果您的新程序通过 CreateProcess 生成旧程序,那么您可以很容易地杀死它并重新创建它。 -
是的@Skizz 创建/终止过程运行良好。现在我还没有在旧程序和新程序(启动器)之间实现任何类型的通信。正如 Mark Wilkins 所说,我正在尝试找出对于像发出心跳这样简单的事情的最佳方法
标签: c windows ipc keep-alive watchdog