我需要做一个套接字程序的统计打印输出。编辑︰访问正在运行的c + +程序中的方法
我使用方法:听(uint32_t的端口)在C++中的线程监听到指定的端口上的客户端(不止一个)和发送/接收客户的交易/从服务器。
现在我需要写多少个数据包接收/通过此方法发送的日志文件。 我的实现显示在下面的框架:
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)++;
}
}
}
现在我需要访问received_pk和sent_pk同时hub.cpp仍在运行(可能在while循环)
我想到了两个选项:
- 访问received_pk和sent_pk从外部程序:像定义,可以将数据包的信息,而线程,直到运行
问题:我不知道我是否可以访问,而程序执行的变量/方法。
- 或每5秒将received_pk和sent_pk打印到日志文件。
问题:我不知道在多线程中是否有定时器是否有意义。
请任何意见将不胜感激。
Kehinde
问两个完全正交的问题,在一个单一的一个不符合要求的堆栈溢出格式良好。 –
如果我正确地理解了第一个问题,那么“程序”的意思就是“过程”,那么就没有这种可能。 – user3528438
在您的问题中包含代码片段总是一个好主意;对于任何想要回答的人来说都更加清楚,它甚至可以帮助你理解问题所在...... – Pandrei