进程的封装会产生意外行为
Encapsulation of Process creates unexpected behavior
我的任务要求我封装流程处理的原理。
以下是我的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
}
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 在C++中对T*类型执行std::move的意外行为
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 处理除以零会导致<csignal>意外行为
- vscode下的Arduino代码出现意外编译错误
- 使用++运算符会导致意外的结果
- 套接字读取后,我在缓冲区中看到意外输入
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 使用vscode调试时,GDB意外退出
- 此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?
- 尝试将字符串/字符转换为整数会产生意外结果
- 将可变参数函数的参数封装在类实例中
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- C++标头错误 C2238 意外标记";"
- C++中意外的多头值
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- vector.size() 在比较中意外工作
- 使用 malloc() 时出现意外大小
- 封装C++模板
- 进程的封装会产生意外行为