【发布时间】:2019-03-07 03:22:47
【问题描述】:
由于不知道与这个问题相关的关键词,所以无法具体询问。
问题是如果在以下源中运行程序,程序不会立即运行。
#include <iostream>
#include <pcap/pcap.h>
int main() {
bool stop = false;
pcap_t *pcp = nullptr;
pcap_pkthdr *pkthdr = nullptr;
const u_char *packet = nullptr;
char errbuf[PCAP_ERRBUF_SIZE];
int res = 0;
//It works normally. "here" printed.
std::cout << "here"
//----------- I think pcap_open_live() block the program --------------
pcp = pcap_open_live("enp0s3", BUFSIZ, 0, -1, errbuf);
//if run following, the program print "captured!" phrase.
//std::cout << "any string\n";
if (pcp == nullptr) {
return 0;
}
//if run following, the program print "captured!" phrase.
//std::cout << "any string\n";
while (!stop) {
while (res == 0) {
res = pcap_next_ex(pcp, &pkthdr, &packet);
}
if (res < 0) {
stop = true;
} else {
std::cout << "captured!\n";
}
}
return 0;
}
程序在以下两个条件下执行。
- 输入任意键
- 像评论一样打印标准输出
为什么会发生这种情况,程序如何立即运行?
【问题讨论】:
-
你不能调试它以找出它阻塞的地方吗?
-
您使用什么标准来确定程序是否执行? (即,您希望看到的 stdout 上是否有一些特定的输出,或者一些网络行为,或者???)
-
@JeremyFriesner"captured!\n" 我想打印这个短语 -
@Sanjeev 我认为
pcap_next_ex(pcp, &pkthdr, &packet)函数第一次被阻塞了.. -
@김현우 将在 pcap_open 调用中定义超时值,您必须查看它。还将 print("captured") 语句放在 else 块中。如果 pcap_next_ex 返回 0 则超时,在这种情况下您不应该打印捕获的内容。