What happens when I have the following situation:
class A: holds on to dynamically allocated object B's. It will create and destroy these.
class B: has an execute function called by A. Execute will fork() and the child will use execvp to run another process. BUT, a flag can be set so that the parent will not wait for the child (allows it to run in the background).
My question is, what is fork doing in this case? I know that the child has a complete copy of the process of the parent, but I'm a little confused. So does that mean that the child process has its own object A which holds the B? And what happens if B is not waiting, but A deletes the B?
Here is some sample code. Note that it is simplified from what I am actually doing.
class B;
class A
{
public:
void addAction( const std::string &name )
{
_bq.push( new B( name ) );
}
void doActions( bool wait = true )
{
while ( !_bq.empty() )
{
B* b = _bq.front();
b->execute( wait );
_bq.pop();
delete b;
}
}
~A() { //omitted, but just deletes everything in queue }
private:
std::queue<B*> _bq;
};
class B
{
public:
B( const std::string &name )
{
args.push_back( name.c_str() );
args.push_back( NULL );
}
void execute( bool waitForChild )
{
pid_t pid = fork();
if ( pid != 0 )
{
if (waitForChild)
{
int status;
wait( &status );
// check status...
}
}
else
{
execvp( args[0], const_cast<char**>( &args[0] ) );
// problem
exit( 100 );
}
}
private:
std::vector<char*> args;
};