1

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?

  • 1
    This code cannot possibly compile. `pid_` is private variable that cannot be accessed from example(). Please don't post imaginary make-believe code, but a [mcve], instead. Otherwise your question will be voted down and closed. – Sam Varshavchik Apr 16 '16 at 11:57

1 Answers1

0

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
} 
Community
  • 1
  • 1
Teivaz
  • 5,462
  • 4
  • 37
  • 75