已编辑:访问正在运行的 C++ 程序中的方法

edited: accessing a method in a running c++ program

本文关键字:C++ 程序 方法 运行 编辑 访问      更新时间:2023-10-16

我需要对套接字程序进行统计打印。

我在 c++ 线程中使用方法 Listen(uint32_t 端口)来侦听指定端口(多个)上的客户端,并向服务器发送/接收客户端的事务。

现在我需要编写一个日志文件,说明此方法接收/发送了多少数据包。我的实现显示在下面的框架中:

hub.cpp

//set up necessary header
#include <iostream>
....
#include <vector>
//global variables
std::map<uint32_t,long> * received_pk;
std::map<uint32_t,long> * sent_pk;
void Listen(uint32_t port ); // method
int main (int argc, char **argv){
//set up client ports
vector<uint32_t> client_ports;
client_ports.push_back(50002);
client_ports.push_back(50003);
//initialize variables
received_pk = new std::map<uint32_t,uint32_t>();
sent_pk = new std::map<uint32_t,uint32_t>();
  for(uint32_t i=0;i<client_ports.size();i++){
    received_pk->insert(std::pair<uint32_t,uint32_t>(client_ports.at(i),0) );
    sent_pk->insert(std::pair<uint32_t,uint32_t>(client_ports.at(i),0) );
  }
//set up thread
vector<thread*> threads;
for(uint32_t i=0;i<client_ports.size();i++){
  cout << "Create Listener in port " << client_ports.at(i) << endl;
  threads.push_back(new thread(Listen,client_ports.at(i)));
  }
//Wait for the threads to finish
  for(uint32_t i=0;i<client_ports.size();i++){
    threads.at(i)->join();
  }
}
void Listen(uint32_t port){
 ...
set up struct sockaddr_in client, host;
listen on port: port
...
  while(1){
    receive packet from client;
    received_pk->at(port)++;
    check packet type
    if(packet==status packet){
      update the packet id number
    }
    if (packet==transaction){
      send packet to Server
      receive reply
      send reply back to client
      sent_pk->at(port)++;
    }
  }
}

现在我需要在 hub.cpp 仍在运行时访问 received_pk 和sent_pk(可能在 while 循环中)

我想到了两个选择:

  1. 从外部程序访问received_pk和sent_pk:例如定义一个可以在线程运行时获取数据包信息的方法

问题:我不知道我是否可以在程序执行时访问变量/方法。

  1. 或每 5 秒打印一次received_pk和sent_pk到日志文件。

问题:我不知道在多线程中使用计时器是否有意义。

请提供任何建议,我们将不胜感激。

凯欣德

很可能,最简单的解决方案是将数据放在共享内存中。map x有点可疑——你是说std::map<Key, Value>吗?这不太适合共享内存。请改用简单的数组。只有64K端口,sizeof(long long[65536])并不过分。