正确的方式确保单实例和传递参数的Windows C ++控制台应用程序 [英] Correct way to ensure single instance and pass on arguments for Windows c++ console application

查看:85
本文介绍了正确的方式确保单实例和传递参数的Windows C ++控制台应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个简单的Windows控制台c ++应用程序。如果应用程序第二次启动(在同一台计算机上),它不应跨越一个新实例,而是将命令行参数传递给已在运行的实例。



以确保应用程序仅通过使用互斥体在一个实例中运行,但是我无法通知第一个应用程序它已经第二次启动并传递命令行参数。



用例:

listener.exe -start //启动侦听器

listener.exe -stop //停止侦听器

解决方案

第一个侦听器应该等待一个事件对象关闭。当您启动 listener.exe -stop 时,它将只设置全局事件关闭,如果第一个实例正在运行,那么它将退出。需要指定事件对象,以便其他进程引用它。此外,当您第二次启动命令时,它将启动另一个进程,没有带有命令解释器的隐式IPC。



listener.exe -start:



  • 创建命名事件(CreateEvent)


  • 等待主线程中的事件或任何合适的螺纹。 (WaitForSingleObject)


  • 活动开始时


  • listener.exe -stop


    1. 获取处理到命名事件。

    2. 设置事件


    3. 一些参考:
      http://msdn.microsoft.com/en- us / library / windows / desktop / ms686915(v = vs85).aspx


      I’m writing a simple Windows console c++ application. If the application is started a second time (on the same computer) it should not span an new instance but pass command line arguments to the instance already running.

      I have accomplished to ensure that the application only runs in one instance by using mutex but I am unable to notify the first application that it has been started as second time and pass on command line arguments.

      Use case:
      listener.exe -start // starts listener
      listener.exe -stop // stops listener

      解决方案

      The first listener should wait on an event object which is for shutdown. When you launch listener.exe -stop then it will just set the global event for shutdown and if first instance is running then it would exit. Named event object is required in order for the other processes to refer it. Also when you fire command 2nd time it will launch another process there is no implicit IPC with command interpreter.

      listener.exe -start:

      1. Create a named event (CreateEvent)

      2. Wait on the event in the main thread or any suitable thread. (WaitForSingleObject)

      3. On event initiate shutdown

      listener.exe -stop

      1. Get Handle to named event.
      2. Set the event so that the thread of first process knows that shutdown event is fired and it exits

      Some reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686915(v=vs.85).aspx

      这篇关于正确的方式确保单实例和传递参数的Windows C ++控制台应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆