Chromium Mojo(IPC)进程通信演示 c++(4)

news/2024/11/6 10:57:37 标签: c++, chrome

122版本自带的mojom通信例子仅供学习参考:

codelabs\mojo_examples\01-multi-process

其余定义参考文章:

Chromium Mojo(IPC)进程通信演示 c++(2)-CSDN博客

01-mojo-browser.exe 与 01mojo-renderer.exe进程通信完整例子。

一、目录结构:

二、01-mojo-browser.exe 

// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/logging.h"
#include "base/process/launch.h"
#include "base/run_loop.h"
#include "codelabs/mojo_examples/mojom/interface.mojom.h"
#include "codelabs/mojo_examples/process_bootstrapper.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/platform/platform_channel.h"
#include "mojo/public/cpp/system/invitation.h"
#include "mojo/public/cpp/system/message_pipe.h"

mojo::ScopedMessagePipeHandle LaunchAndConnect() {
  // Under the hood, this is essentially always an OS pipe (domain socket pair,
  // Windows named pipe, Fuchsia channel, etc).
  mojo::PlatformChannel channel;

  mojo::OutgoingInvitation invitation;

  // Attach a message pipe to be extracted by the receiver. The other end of the
  // pipe is returned for us to use locally. We choose the arbitrary name "pipe"
  // here, which is the same name that the receiver will have to use when
  // plucking this pipe off of the invitation it receives to join our process
  // network.
  mojo::ScopedMessagePipeHandle pipe = invitation.AttachMessagePipe("pipe");

  base::LaunchOptions options;
  // This is the relative path to the mock "renderer process" binary. We pass it
  // into `base::LaunchProcess` to run the binary in a new process.
  static const base::CommandLine::CharType* argv[] = {
      FILE_PATH_LITERAL("./01-mojo-renderer")};
  base::CommandLine command_line(1, argv);

  // Delegating to Mojo to "prepare" the command line will append the
  // `--mojo-platform-channel-handle=N` command line argument, so that the
  // renderer knows which file descriptor name to recover, in order to establish
  // the primordial connection with this process. We log the full command line
  // next, to show what mojo information the renderer will be initiated with.
  channel.PrepareToPassRemoteEndpoint(&options, &command_line);
  LOG(INFO) << "Browser: " << command_line.GetCommandLineString();
  base::Process child_process = base::LaunchProcess(command_line, options);
  channel.RemoteProcessLaunchAttempted();

  mojo::OutgoingInvitation::Send(std::move(invitation), child_process.Handle(),
                                 channel.TakeLocalEndpoint());
  return pipe;
}

void CreateProcessRemote(mojo::ScopedMessagePipeHandle pipe) {
  mojo::PendingRemote<codelabs::mojom::Process> pending_remote(std::move(pipe),
                                                               0u);
  mojo::Remote<codelabs::mojom::Process> remote(std::move(pending_remote));
  LOG(INFO) << "Browser invoking SayHello() on remote pointing to renderer";
  remote->SayHello();
}

int main(int argc, char** argv) {
  LOG(INFO) << "'Browser process' starting up";
  base::CommandLine::Init(argc, argv);
  ProcessBootstrapper bootstrapper;
  bootstrapper.InitMainThread(base::MessagePumpType::IO);
  bootstrapper.InitMojo(/*as_browser_process=*/true);

  mojo::ScopedMessagePipeHandle pipe = LaunchAndConnect();
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindOnce(&CreateProcessRemote, std::move(pipe)));

  base::RunLoop run_loop;
  // Delay shutdown of the browser process for visual effects, as well as to
  // ensure the browser process doesn't die while the IPC message is still being
  // sent to the target process asynchronously, which would prevent its
  // delivery.
  base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(
          [](base::OnceClosure quit_closure) {
            LOG(INFO) << "'Browser process' shutting down";
            std::move(quit_closure).Run();
          },
          run_loop.QuitClosure()),
      base::Seconds(2));
  run_loop.Run();
  return 0;
}

三、01-mojo-renderer.exe

// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/logging.h"
#include "base/run_loop.h"
#include "codelabs/mojo_examples/mojom/interface.mojom.h"
#include "codelabs/mojo_examples/process_bootstrapper.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/platform/platform_channel.h"
#include "mojo/public/cpp/system/invitation.h"
#include "mojo/public/cpp/system/message_pipe.h"

class ProcessImpl : public codelabs::mojom::Process {
 public:
  explicit ProcessImpl(
      mojo::PendingReceiver<codelabs::mojom::Process> pending_receiver) {
    receiver_.Bind(std::move(pending_receiver));
  }

 private:
  // codelabs::mojo::Process
  void GetAssociatedInterface(
      const std::string&,
      mojo::PendingAssociatedReceiver<codelabs::mojom::GenericInterface>)
      override {
    NOTREACHED();
  }
  void SayHello() override { LOG(INFO) << "Hello!"; }

  mojo::Receiver<codelabs::mojom::Process> receiver_{this};
};
ProcessImpl* g_process_impl = nullptr;

void BindProcessImpl(mojo::ScopedMessagePipeHandle pipe) {
  // Create a receiver
  mojo::PendingReceiver<codelabs::mojom::Process> pending_receiver(
      std::move(pipe));
  g_process_impl = new ProcessImpl(std::move(pending_receiver));
}

int main(int argc, char** argv) {
  base::CommandLine::Init(argc, argv);
  // Logging the entire command line shows all of the information that the
  // browser seeded the renderer with. Notably, this includes the mojo platform
  // channel handle that the renderer will use to bootstrap its primordial
  // connection with the browser process.
  LOG(INFO) << "Renderer: "
            << base::CommandLine::ForCurrentProcess()->GetCommandLineString();

  ProcessBootstrapper bootstrapper;
  bootstrapper.InitMainThread(base::MessagePumpType::IO);
  bootstrapper.InitMojo(/*as_browser_process=*/false);

  // Accept an invitation.
  //
  // `RecoverPassedEndpointFromCommandLine()` is what makes use of the mojo
  // platform channel handle that gets printed in the above `LOG()`; this is the
  // file descriptor of the first connection that this process shares with the
  // browser.
  mojo::IncomingInvitation invitation = mojo::IncomingInvitation::Accept(
      mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine(
          *base::CommandLine::ForCurrentProcess()));
  // Extract one end of the first pipe by the name that the browser process
  // added this pipe to the invitation by.
  mojo::ScopedMessagePipeHandle pipe = invitation.ExtractMessagePipe("pipe");

  base::RunLoop run_loop;
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindOnce(&BindProcessImpl, std::move(pipe)));
  run_loop.Run();
  return 0;
}

四、编译

 1、gn gen out/debug

 2、 ninja -C out/debug 01-mojo-browser

     生成01-mojo-browser.exe

3、ninja -C out/debug 01-mojo-renderer

      生成01-mojo-renderer.exe


http://www.niftyadmin.cn/n/5740797.html

相关文章

常用的c++新特性--> day02

可调用对象 案例 #include <iostream> #include <string> #include <vector> using namespace std;using funcptr void(*)(int, string);int print(int a, double b) {cout << a << ", " << b << endl;return 0; } // …

unity3d————屏幕坐标,GUI坐标,世界坐标的基础注意点

在Unity3D中&#xff0c;GUI控件的起始坐标与屏幕坐标的起始点并不完全相同&#xff0c;具体说明如下&#xff1a; GUI控件的起始坐标 绘制GUI界面时使用的坐标以屏幕的左上角为(0,0)点&#xff0c;右下角为(Screen.width, Screen.Height)。不过&#xff0c;对于GUI控件的具体…

无人机之姿态融合算法篇

无人机的姿态融合算法是无人机飞行控制中的核心技术之一&#xff0c;它通过将来自不同传感器的数据进行融合&#xff0c;以实现更加精确、可靠的姿态检测。 一、传感器选择与数据预处理 无人机姿态融合算法通常依赖于多种传感器&#xff0c;包括加速度计、陀螺仪、磁力计等。这…

[Web安全 网络安全]-DoS(拒绝服务攻击)和DDoS(分布式拒绝服务攻击)

文章目录&#xff1a; 一&#xff1a;前言 1.DoS攻击 2.DDoS攻击 3.DoS攻击和DoS攻击的异同 4.原理 5.攻击流程 6.分类 7.影响 8.防御 9.工具 二&#xff1a;攻击方式 一&#xff1a;前言 1.DoS攻击 DoS攻击&#xff0c;即拒绝服务攻击故意的攻击网络协议实现的缺…

浅谈QT中Tab键的切换逻辑

浅谈QT中Tab键的切换逻辑 无意中发现在输入界面中按下Tab键时&#xff0c;没有按照预想的顺序切换焦点事件&#xff0c;如下图所示 这个现象还是很有趣&#xff0c;仔细观察了下&#xff0c;默认的切换顺序是按照控件拖入顺序&#xff0c;那么知道了这个问题想要解决起来就很简…

C#开发流程

注&#xff1a;检查数据库链接 设置搜索 1.新建模块文件夹 对应应用 右键-添加-新建文件夹 2.新建类 在新建模块下右键 新建-类&#xff0c;修改类名称 修改internal为public 新建所需字段&#xff0c;注意类型声明及必填设置 [SugarColumn(IsNullable false)]public strin…

APP开发者如何选择合适的聚合平台?

选择合适的 App 聚合平台对于开发者而言&#xff0c;无疑是一项具有深远影响的重要决策&#xff0c;其意义之重大&#xff0c;直接关乎着 App 的收益、用户体验以及市场覆盖的广度与深度。 就拿收益这一方面来说&#xff0c;App 的收益直接决定了开发者的投入产出比以及后续的…

【数据仓库】Hive 拉链表实践

背景 拉链表是一种数据模型&#xff0c;主要是针对数据仓库设计中表存储数据的方式而定义的&#xff1b;顾名思义&#xff0c;所谓拉链表&#xff0c;就是记录历史。记录一个事务从开始一直到当前状态的所有变化的信息。 拉链表可以避免按每一天存储所有记录造成的海量存储问题…