加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

单个C程序实例,使用boost :: interprocess

发布时间:2020-12-16 09:55:07 所属栏目:百科 来源:网络整理
导读:我有一个控制台应用程序,我试图只能一次运行一次.我使用了boost进程库shared_memory_object来做到这一点.请参阅下面的代码段, boost::scoped_ptrshared_memory_object sharedMem; try { sharedMem.reset( new shared_memory_object(create_only,"shared_memo
我有一个控制台应用程序,我试图只能一次运行一次.我使用了boost进程库shared_memory_object来做到这一点.请参阅下面的代码段,

boost::scoped_ptr<shared_memory_object> sharedMem;

  try
  {
     sharedMem.reset(
       new shared_memory_object(create_only,"shared_memory",read_write));
  } catch(...)
  {
     // executable is already running
      cerr << "Another instance of this program is running!" << endl;
      return 1;
  }

  // do something

  shared_memory_object::remove("shared_memory");  // remove the shared memory before exiting the application

问题是,该方法可以防止我的应用程序同时运行多次;但是,让我们假设用户停止程序运行,然后内存将不会被释放,下次当用户再次尝试运行程序时,它将无法运行.你有什么建议吗 ?

附: C控制台应用程序,操作系统:Ubuntu(但是一个可以在其他平台上运行的解决方案也是完美的).
谢谢

解决方法

您需要做的是捕获程序的意外终止并相应地释放共享内存对象.您可以使用signal.h POSIX标头捕获SIGINT:

#include <signal.h>

void handleSIGINT(int param=0) {
    // Reset the shared memory object here
}

int main() {

   // Connect the signal handler to SIGINT
   signal(SIGINT,handleSIGINT);

   // Etc...

}

您可以使用atexit()函数以相同的方式捕获程序终止.文件here.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读