c – 如何运行一个应用程序实例

我有一个应用程序使用套接字连接从另一个应用程序发送和接收数据.在创建套接字时,它使用端口4998.

那就是我的问题所在.一旦我启动我的应用程序,套接字开始使用端口4998.所以如果我要再次执行该应用程序,我得到套接字绑定错误.

所以我想将我的应用程序实例限制在一个.这意味着如果应用程序已经在运行,并且有一些尝试通过单击exe或快捷方式图标再次运行该应用程序,则它不应该运行该程序,而应该将现有的应用程序带到Top.

解决方法

您可以使用命名的互斥体.

article代码示例:

WINAPI WinMain(
  HINSTANCE,HINSTANCE,LPSTR,int)
{
  try {
    // Try to open the mutex.
    HANDLE hMutex = OpenMutex(
      MUTEX_ALL_ACCESS,"MyApp1.0");

    if (!hMutex)
      // Mutex doesn’t exist. This is
      // the first instance so create
      // the mutex.
      hMutex = 
        CreateMutex(0,"MyApp1.0");
    else
      // The mutex exists so this is the
      // the second instance so return.
      return 0;

    Application->Initialize();
    Application->CreateForm(
      __classid(TForm1),&Form1);
    Application->Run();

    // The app is closing so release
    // the mutex.
    ReleaseMutex(hMutex);
  }
  catch (Exception &exception) {
    Application->
      ShowException(&exception);
  }
  return 0;
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...