C ++ and fork-exec resource release?

I am trying to create a new process from my C ++ project using fork-exec. I use fork-exec to create a bidirectional pipe for a child process. But I am afraid that my resources in the forked process will not be freed properly, as the call to exec will completely capture my process and will not name any destructors.

I tried to get around this by throwing an exception and calling execl from the catch block at the end of main, but this solution does not kill any singleton.

Is there any reasonable way to achieve this safely? (hopefully avoiding any atExit hackers)

Ex: the following code outputs:

We are the child, gogo!
Parent proc, do nothing
Destroying object

Although the forked process also has a copy of the singleton, which must be destroyed before I call 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;
}
+5
1

, fork exec. , fork , , , exec . ? - , , , - , ? , .

, . : , - stdout fork, . fclose fflush stdout , ! ( _exit exit, exec .)

, , . - ( stdio FILE iostream), exec. - FD_CLOEXEC ( open, ) / 3 , close (not fclose) . (FreeBSD closefrom, , , , , .)

- , - - , , exec , . , pthread_atfork, , . , , - " , fork", .

+3

All Articles