2016-03-02 29 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

我沒有包括骨架中的刪除。我在主代碼中刪除了。你能多解釋一下共享內存嗎? –

相關問題