2016-03-02 47 views
-1

我需要做一个套接字程序的统计打印输出。编辑︰访问正在运行的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循环)

我想到了两个选项:

  1. 访问received_pk和sent_pk从外部程序:像定义,可以将数据包的信息,而线程,直到运行
012的方法

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

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

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

请任何意见将不胜感激。

Kehinde

+0

问两个完全正交的问题,在一个单一的一个不符合要求的堆栈溢出格式良好。 –

+0

如果我正确地理解了第一个问题,那么“程序”的意思就是“过程”,那么就没有这种可能。 – user3528438

+0

在您的问题中包含代码片段总是一个好主意;对于任何想要回答的人来说都更加清楚,它甚至可以帮助你理解问题所在...... – Pandrei

回答

0

很可能,最简单的解决办法是把数据中共享存储器map x有点怀疑 - 你的意思是std::map<Key, Value>?这不适合共享内存。相反,使用简单的数组。只有64K端口,而sizeof(long long[65536])并不过分。

+0

@MSalter嗨,感谢您的回答,我加入我的代码骨架修饰后。你可以请再次检查谢谢 –

+0

是的 - 该地图不适合共享内存。另外,太多的'新'电话。 (还不够'删除',但这是一个单独的问题) – MSalters

+0

我没有包括骨架中的删除。我在主代码中删除了。你能多解释一下共享内存吗? –

相关问题