如何避免共享内存泄漏

时间:2014-03-27 15:05:52

标签: linux shared-memory

我在Suse Linux上的两个进程之间使用共享内存,我想知道如何在一个进程崩溃或两者都崩溃的情况下避免共享内存泄漏。在这种情况下是否发生泄漏?如果是,我该如何避免呢?

2 个答案:

答案 0 :(得分:1)

您可以为共享内存区域中的两个计数器分配空间:每个进程一个。每隔几秒钟,每个进程递增其计数器,并检查另一个计数器是否也已递增。这使得这两个进程或外部监视程序很容易在有人崩溃或退出时拆除共享内存。

答案 1 :(得分:0)

  • 如果子流程是父流程中的简单$errors = new MessageBag(); $validator = Validator::make(Input::all(), [ "blended" => "required|numeric|min:0.1", ], [ 'blended.required' => 'Please enter a valid weight', 'blended.min' => 'Please enter the weight you blended', 'blended.numeric' => 'Invalid weight blended', ]); if( $validator->fails() ) { $errors->add('blended', 'Please enter a valid weight'); alert()->overlay('Error!', 'Errors: Wrong weight was given', 'error'); return Redirect::route('roast.index'); } $blend_id = $request->blend_id; $blend_weight = $request->blended * 1000; // Blend - Get coffees and their weights for the blend $blend_coffees = $this->getBlendCoffeesWeight($blend_id, $blend_weight); foreach($blend_coffees as $cof) { $have = 'none'; $coffee_id = $cof['coffee_id']; $roasted = $this->getTotalRoasted($coffee_id); $packed = $this->getTotalCoffeePacked($coffee_id); $blended = $this->getTotalCoffeeBlended($coffee_id); $total_weight_packed = $shop_usage = $this->getTotalShopUsage($coffee_id); $weight_left = $roasted - $packed['total'] - $blended - $shop_usage; //Not enough to pack and not Blend Anyway if($weight_left < $cof['weight'] && $request->blend_anyway == 0) { $coffee_name = Coffee::find($coffee_id); $coffee_name = $coffee_name->name; $need = $this->convertWeight($cof['weight']); $have = $this->convertWeight($weight_left); $errors->add('weight', "You need: $need of $coffee_name but you have: $have"); } else { //Creating an array for the table updates later $blends[] = array('coffee_id'=>$coffee_id, 'blended'=>$blend_coffees[$coffee_id]['weight']); } } if($errors->any()) { alert()->error('Error!', 'You cannot blend please check the errors'); return Redirect::route('roast.index')->withErrors($errors); ,则fork()mmap()应该可以工作。

  • 如果子进程执行MAP_SHARED以启动其他可执行文件,则通常可以通过exec()或类似的非便携式系统调用传递文件描述符(请参见Is there anything like shm_open() without filename?)在包括Linux在内的许多操作系统上,您可以shm_open()shm_unlink()的文件描述符,这样它就不会在进程终止时泄漏内存,并使用shm_open()来清除关闭状态。 shm文件描述符上的exec标志,以便您的子进程可以跨exec继承它。这在POSIX标准中没有很好的定义,但是在实践中似乎很容易移植。

  • 如果您需要使用文件名而不是文件描述符号来将共享内存对象传递给不相关的进程,那么您必须想办法自己fcntl()来处理文件不再需要;请参阅John Zwinck的答案中的一种方法。