The essentials of C++ multi-threaded system programming of muduo library learning 06-RAII and fork

Dongyang's study notes

审慎Use fork()

fork() may cause resource leakage

However, if the program will fork(), the above assumption will be broken.
Consider the following example, the Foo object is constructed once, but destructed twice

int main()
{
    
    
    Foo foo;    //调用构造函数
    fork();     //fork为两个进程
    foo.doit(); //在父子进程中都使用foo
 
    //析构函数会被调用两次,父进程和子进程各一次
}
  • 还可能会出现的错误: If the Foo class encapsulates a certain resource, and this resource is not inherited by the child process, then the function of Foo::doit() is messy in the child process. And we have no way to prevent this automatically. We can't call pthread_atfork() every time we apply for a resource, right?

The child process 继承and不继承

  • After fork(), the child process inherits almost all the state of the parent process, but there are a few exceptions
  • **The child process inherits the address space and file descriptors,** so the RAII class used to manage dynamic memory and file descriptors can work normally
  • But the child process will not inherit:
    • The memory lock of the parent process, mlock, mlockall
    • File lock of the parent process, fcntl
    • Some timers of the parent process, setitimer, alarm, timer_create, etc.

For more see https://blog.csdn.net/qq_22473333/article/details/113481494#t3

Notes on RAII and fork()

  • Usually we use the RAII method to manage the above types of resources (locking and unlocking, creating and destroying timers, etc.), but it may not work properly in the child process from fork(), because the resources have been released during fork() Up
  • For example, use RAII technique to encapsulate timer_create()/timer_delete():
    • The destructor call timer_delete() in the child process may make an error because it tries to release a non-existent resource
    • Or worse, release the timer held by other objects (if the new timer_t happens to be a duplicate of it)
  • Therefore, when we are writing server-side programs, "whether fork() is allowed" is a question that should be carefully considered at the beginning. If you use fork() in a program that is not prepared for fork(), you will encounter Unforeseen problems

Guess you like

Origin blog.csdn.net/qq_22473333/article/details/113529880