我想从我的C++项目中使用fork-exec产生一个新进程。我正在使用fork-exec来为子进程创建一个双向管道。但是我担心分叉进程中的资源不会被正确释放,因为exec-call将完全接管我的进程并且不会调用任何析构函数。释放C++资源和fork-exec?
我试图通过在主月底从catch块抛出异常并调用EXECL规避这一点,但这种方法不破坏任何单身。
是否有任何明智的方法来实现这一安全? (希望避免任何atexit对黑客)
实施例:下面的代码输出:
We are the child, gogo!
Parent proc, do nothing
Destroying object
即使两岔过程还具有需要之前我请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[])
{
try
{
Resources& ref = getRes();
makeChild("child");
}
catch(const string &command)
{
execl(command.c_str(), "");
}
return 0;
}
你在谈论哪些资源?大多数文件描述符都存在于exec()中,您可以标记close-on-exec,以便内核为您关闭它们。 http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html – 2011-01-11 20:48:38
顺便说一下,如果析构函数在分叉的子代以及父代中被调用,它最终会调用构造函数一次(在父代中)和析构函数两次(都在父母和孩子中)。 – 2011-01-11 20:51:23