我想從我的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