My assignment requires me to encapsulate the principle of process handling.
Here's what my Process class contains:
class Process
{
public:
Process();
~Process();
pid_t getPid() const;
private:
pid_t pid_;
};
Constructor:
Process::Process()
{
this->pid_ = fork();
}
Destructor:
Process::~Process()
{
if (this->pid_ > 0)
kill(this->pid_, SIGKILL);
}
Here's the problem: after encapsulating and creating an object like such:
void example()
{
Process pro;
if (pro.pid_ == 0)
{
// Child Process
}
else if (pro.pid_ < 0)
{
// Error
}
else
{
// Parent Process
}
}
My program almost never enters the child code, but when I fork()
normally (with no encapsulation) it works like a charm.
Where did I go wrong? How may I synchronize the child and parent to be sure that they both do their jobs?
I can't verify your example but I see an obvious flaw in your class Process. It defines custom constructor and destructor but assignment operator is not defined which violates the rule of three.
Consider following code:
void example()
{
Process pro;
{
Process pro2 = pro;
}
// here pro.pid_ will have id of the already killed process
}