进程的封装会产生意外行为

Encapsulation of Process creates unexpected behavior

本文关键字:意外 封装 进程      更新时间:2023-10-16

我的任务要求我封装流程处理的原理。

以下是我的Process类包含的内容:

class Process
{
public:
  Process();
  ~Process();
  pid_t getPid() const;
private:
  pid_t         pid_;
};

施工单位:

Process::Process()
{
  this->pid_ = fork();
}

破坏者:

Process::~Process()
{
  if (this->pid_ > 0)
    kill(this->pid_, SIGKILL);
}

问题是:在封装并创建这样的对象之后:

void    example()
{
  Process       pro;
  if (pro.pid_ == 0)
    {
      // Child Process                                                                                                      
    }
  else if (pro.pid_ < 0)
    {
      // Error                                                                                                         
    }
  else
    {
      // Parent Process                                                                                                     
    }
}

我的程序几乎从不输入子代码,但当我正常地fork()(没有封装)时,它就像一个魅力。

我哪里错了?我如何同步孩子和家长以确保他们都能完成自己的工作?

我无法验证您的示例,但我在您的类Process中看到了一个明显的缺陷。它定义了自定义构造函数和析构函数,但没有定义赋值运算符,这违反了三规则。

考虑以下代码:

void example()
{
   Process pro;
   {
      Process pro2 = pro;
   }
   // here pro.pid_ will have id of the already killed process
}