如何在c ++中正确使用ifstreams,使用子进程并避免泄漏?

问题描述 投票:0回答:1

我正在尝试创建一个比萨店模拟,以了解有关子流程和线程的更多信息。我想最大限度地避免内存泄漏。

目前,当我只创建一个厨房时没有错误,但是当我创建2个或更多时,我在销毁时遇到了ifstreams和ofstreams的泄漏。

有main():

int main(int argc __attribute__((unused)), char const *argv[] __attribute__((unused)))
{
    Kitchen k(0, 2, 30);
    Kitchen k2(0, 2, 30);

    return 0;
}

Kitchen.hpp:

class Kitchen {
    private:

        bool                                _IsFull = false;
        int                                 _Pid = 0;

        int                                 _CookTime;
        int                                 _MaxCooks;
        long                                _RefreshDelay;
        double                              _MaxTime = 5;
        unsigned long int                   _QueueSize;

        std::ofstream                       _Opipe;
        std::ifstream                       _Ipipe;
        unsigned int                        _Door = 0;
        std::string                         _FallIn = "";
        std::string                         _FallOut = "";

        void CooksAwakening (void);
        void CleaningTime (void);
        void OpenPipe (void);
        void Quit (void);
        void Run (void);

    public:
        explicit Kitchen (int CookingTime, int MaxCooks, long RefreshDelay);
        virtual ~Kitchen ();

        bool IsFull () const { return _IsFull; }
        int GetPid () const { return _Pid; }
    };

还有Kitchen.cpp:

int Knum = 0;

Kitchen::Kitchen(int CookingTime, int MaxCooks, long RefreshDelay)
: _CookTime(CookingTime), _MaxCooks(MaxCooks), _RefreshDelay(RefreshDelay), _QueueSize(_MaxCooks * 2)
{
    OpenPipe();
    _Pid = fork();
    if (_Pid == 0) {
        _Opipe.open(_FallIn.c_str(), std::ostream::out);
        _Ipipe.open(_FallOut.c_str(), std::istream::in);
        Run();
    } else {
        _Ipipe.open(_FallIn.c_str(), std::istream::in);   // Valgrind point this line
        _Opipe.open(_FallOut.c_str(), std::ostream::out); // Valgrind point this line too
    }
}

Kitchen::~Kitchen()
{
    if (_Pid == 0) {
    } else {
        _Opipe << "QUIT" << std::endl;
        _Ipipe.close();
        _Opipe.close();
        unlink(_FallIn.c_str());
        unlink(_FallOut.c_str());
    }
}

void Kitchen::Quit(void)
{
    CleaningTime();
    _Ipipe.close();
    _Opipe.close();
    exit(0);
}

void Kitchen::CleaningTime(void)
{
    while (!_Cooks.empty()) {
        _Cooks.pop_back();
    }
    while (!_PizzaQueue.empty()) {
        _PizzaQueue.pop_back();
    }
    _Cooks.shrink_to_fit();
    _PizzaQueue.shrink_to_fit();
}

void Kitchen::OpenPipe(void)
{
    std::cout << "Kit Open Pipes\t" << getpid() << '\n';
    std::ostringstream       oss1;
    oss1 << "/tmp/kint" << Knum;
    _FallIn = oss1.str();

    std::ostringstream      oss2;
    oss2 << "/tmp/kout" << Knum;
    _FallOut = oss2.str();

    _Door = Knum;
    ++Knum;

    if (mkfifo(_FallOut.c_str(), 0666) != 0) {
        perror ("mkfifo1");
        exit(84);
    }
    if (mkfifo(_FallIn.c_str(), 0666) != 0) {
        perror("mkfifo2");
        exit(84);
    }
}

void    Kitchen::Run(void)
{
    std::string cmd;

    while (_Ipipe >> cmd)
    {
        if (cmd == "QUIT") {
            Quit();
        }
    }
    Quit();
}

这是valgrind的结果:

total heap usage: 36 allocs, 32 frees, 109,712 bytes allocated
==20890== 
==20890== 552 bytes in 1 blocks are still reachable in loss record 1 of 4
==20890==    at 0x483880B: malloc (vg_replace_malloc.c:309)
==20890==    by 0x4C1536E: __fopen_internal (in /usr/lib64/libc-2.28.so)
==20890==    by 0x4925AA3: std::__basic_file<char>::open(char const*, std::_Ios_Openmode, int) (in /usr/lib64/libstdc++.so.6.0.25)
==20890==    by 0x496789D: std::basic_filebuf<char, std::char_traits<char> >::open(char const*, std::_Ios_Openmode) (in /usr/lib64/libstdc++.so.6.0.25)
==20890==    by 0x4967A73: std::basic_ifstream<char, std::char_traits<char> >::open(char const*, std::_Ios_Openmode) (in /usr/lib64/libstdc++.so.6.0.25)
==20890==    by 0x4052F2: WorkSpace::Kitchen::Kitchen(int, int, long) (Kitchen.cpp:36)
==20890==    by 0x40250C: main (main.cpp:46)
==20890== 
==20890== 552 bytes in 1 blocks are still reachable in loss record 2 of 4
==20890==    at 0x483880B: malloc (vg_replace_malloc.c:309)
==20890==    by 0x4C1536E: __fopen_internal (in /usr/lib64/libc-2.28.so)
==20890==    by 0x4925AA3: std::__basic_file<char>::open(char const*, std::_Ios_Openmode, int) (in /usr/lib64/libstdc++.so.6.0.25)
==20890==    by 0x496789D: std::basic_filebuf<char, std::char_traits<char> >::open(char const*, std::_Ios_Openmode) (in /usr/lib64/libstdc++.so.6.0.25)
==20890==    by 0x4967AC3: std::basic_ofstream<char, std::char_traits<char> >::open(char const*, std::_Ios_Openmode) (in /usr/lib64/libstdc++.so.6.0.25)
==20890==    by 0x40531C: WorkSpace::Kitchen::Kitchen(int, int, long) (Kitchen.cpp:37)
==20890==    by 0x40250C: main (main.cpp:46)
==20890== 
==20890== 8,192 bytes in 1 blocks are still reachable in loss record 3 of 4
==20890==    at 0x4839593: operator new[](unsigned long) (vg_replace_malloc.c:433)
==20890==    by 0x496358F: std::basic_filebuf<char, std::char_traits<char> >::_M_allocate_internal_buffer() (in /usr/lib64/libstdc++.so.6.0.25)
==20890==    by 0x49678B5: std::basic_filebuf<char, std::char_traits<char> >::open(char const*, std::_Ios_Openmode) (in /usr/lib64/libstdc++.so.6.0.25)
==20890==    by 0x4967A73: std::basic_ifstream<char, std::char_traits<char> >::open(char const*, std::_Ios_Openmode) (in /usr/lib64/libstdc++.so.6.0.25)
==20890==    by 0x4052F2: WorkSpace::Kitchen::Kitchen(int, int, long) (Kitchen.cpp:36)
==20890==    by 0x40250C: main (main.cpp:46)
==20890== 
==20890== 8,192 bytes in 1 blocks are still reachable in loss record 4 of 4
==20890==    at 0x4839593: operator new[](unsigned long) (vg_replace_malloc.c:433)
==20890==    by 0x496358F: std::basic_filebuf<char, std::char_traits<char> >::_M_allocate_internal_buffer() (in /usr/lib64/libstdc++.so.6.0.25)
==20890==    by 0x49678B5: std::basic_filebuf<char, std::char_traits<char> >::open(char const*, std::_Ios_Openmode) (in /usr/lib64/libstdc++.so.6.0.25)
==20890==    by 0x4967AC3: std::basic_ofstream<char, std::char_traits<char> >::open(char const*, std::_Ios_Openmode) (in /usr/lib64/libstdc++.so.6.0.25)
==20890==    by 0x40531C: WorkSpace::Kitchen::Kitchen(int, int, long) (Kitchen.cpp:37)
==20890==    by 0x40250C: main (main.cpp:46)
==20890== 
==20890== LEAK SUMMARY:
==20890==    definitely lost: 0 bytes in 0 blocks
==20890==    indirectly lost: 0 bytes in 0 blocks
==20890==      possibly lost: 0 bytes in 0 blocks
==20890==    still reachable: 17,488 bytes in 4 blocks
==20890==         suppressed: 0 bytes in 0 block

我用gcc和这些标志编译:-Wall -Wextra -Weffc ++

valgrind命令如下:valgrind --leak-check = full --show-leak-kinds = all ./plazza

c++ valgrind ifstream ofstream
1个回答
0
投票

显示的代码在子进程中执行以下操作:

void Kitchen::Quit(void)
{
    CleaningTime();
    _Ipipe.close();
    _Opipe.close();
    exit(0);
}

即使手动关闭打开的流,此时这些对象仍然存在,并且exit(0)立即终止该过程。

尽管实际文件已关闭,但流对象仍然存在,并且仍然为它们的内部流缓冲区分配了一些内存。当这些对象被正确销毁时,该内存才会被释放,这不会通过exit(0)发生。

exit(0)是一个标准的C库函数,它对任何C ++对象都不了解。它只是从高轨道上破坏了这个过程。

valgrind检测到子进程终止而没有完全释放它分配的所有内存,并报告。

要“在C ++中正确使用带有子进程的ifstreams并避免泄漏”,子进程必须以与主进程终止相同的方式终止:从main()返回。在终止它之前,这显然会在子进程中销毁自动和静态作用域中的所有对象。

就程序逻辑上的工作方式而言,这显然会带来几个难以解决的问题。一种常用的蛮力方法通常是抛出异常而不是exit()ing,它会被main()捕获。当然,这只适用于在抛出异常时构造正常的代码。

© www.soinside.com 2019 - 2024. All rights reserved.