我正在尝试使用fork-exec从我的C++项目中生成一个新进程.我正在使用fork-exec来创建子进程的双向管道.但是我担心分叉进程中的资源不会被正确释放,因为exec-call将完全接管我的进程并且不会调用任何析构函数.
我尝试通过抛出异常并在main的末尾从catch块调用execl来绕过这个,但是这个解决方案并没有破坏任何单例.
有没有明智的方法来安全地实现这一目标?(希望避免任何atExit黑客攻击)
例如:以下代码输出:
We are the child, gogo!
Parent proc, do nothing
Destroying object
Run Code Online (Sandbox Code Playgroud)
即使分叉进程也有一个单例的副本,在我调用execl之前需要对其进行破坏.
#include <iostream>
#include <unistd.h>
using namespace std;
class Resources
{
public:
~Resources() { cout<<"Destroying object\n"; }
};
Resources& getRes()
{
static Resources r1;
return r1;
}
void makeChild(const string &command)
{
int pid = fork();
switch(pid)
{
case -1:
cout<<"Big error! Wtf!\n";
return;
case 0:
cout<<"Parent proc, do nothing\n";
return;
}
cout<<"We are the child, gogo!\n";
throw command;
}
int main(int argc, char* argv[]) …Run Code Online (Sandbox Code Playgroud)