我最近一直在編寫一個netflow接收器,通過UDP監聽netflow。一旦它處理了流數據報,它將它寫入syslog。我的問題是,一旦我收到標準recvfrom函數的數據報包,我的消息就不會再傳給syslog了。我正在接收和處理數據,但系統日誌寫入不起作用。代碼如下所示C recvfrom打破系統日誌
setlogmask(LOG_UPTO(LOG_NOTICE));
openlog("netflow_receiver", LOG_CONS, LOG_LOCAL2);
syslog(LOG_NOTICE, "Syslogger started");
while(1){
syslog(LOG_NOTICE, "Top of loop");
unsigned char* mesg = (unsigned char*)malloc(1024 * sizeof(unsigned char));
syslog(LOG_NOTICE, "Allocated message memory");
len = sizeof(cliaddr);
syslog(LOG_NOTICE, "Got len of client");
//Syslog stops after this
n = recvfrom(sockfd, mesg, 1024, 0, (struct sockaddr *) &cliaddr, &len);
syslog(LOG_NOTICE, "received");
mesg[n] = 0;
syslog(LOG_NOTICE, "Calling log_record");
process_record(mesg);
syslog(LOG_NOTICE, "Back from log_record");
}
系統日誌看起來就像這樣
Dec 12 09:42:01 my_pc netflow_receiver: Syslogger started
Dec 12 09:42:01 my_pc netflow_receiver: Top of loop
Dec 12 09:42:01 my_pc netflow_receiver: Allocated message memory
Dec 12 09:42:01 my_pc netflow_receiver: Got len of client
Dec 12 09:48:33 my_pc netflow_receiver: Syslogger started
Dec 12 09:48:33 my_pc netflow_receiver: Top of loop
Dec 12 09:48:33 my_pc netflow_receiver: Allocated message memory
...
任何想法或建議...我願意,如果有人知道一個使用非標準C庫的syslog好的。
[請不要在C]中輸入'malloc()'的返回值(http://stackoverflow.com/a/605858/28169)。也不要用'sizeof(char)'來縮放,它總是1,所以它不會增加代碼的質量,但會增加很多噪音。你的分配應該是:'unsigned char * msg = malloc(1024);'。布拉姆。 – unwind
感謝您對malloc的鑄造建議。以前從未遇到過任何問題,但這很好理解。不過,我總是會使用'needed_size * sizeof(type)',因爲這是我的編碼風格,我喜歡確保從malloc中獲得正確的數量,而不管它是多麼隱含。 – Tommy