gpt4 book ai didi

c++ - alarm() 在随机时间后生成 SIGALRM

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:33:43 26 4
gpt4 key购买 nike

我正在尝试制作一个程序,它将解析 pcap 文件直到计时器到期。我为此使用了 alarm 函数,found here ,这确实会停止 pcap_loop,但绝对不会在给定时间后停止。

重要部分代码:

pcap_t *handle;

void end_loop(int signum)
{
pcap_breakloop(handle);
}

int main(...){
...
handle = pcap_open_live(argv[2], BUFSIZ, 1, 100, errbuf);
....
signal(SIGALRM, end_loop);
alarm(5);
pcap_loop(handle, num_packets, got_packet, NULL);
pcap_close(handle);
send_syslog_message(hostname, list_of_parsed_packets));
return 0;
}

我试过多次运行这个程序,它总是停止,但正如标题所说,它所花费的时间只是随机的。我做错了什么吗?

最佳答案

man pcap_breakloop说:

The flag is checked in loops reading packets from the OS - a signal by itself will not necessarily terminate those loops - as well as in loops processing a set of packets returned by the OS. Note that if you are catching signals on UNIX systems that support restarting system calls after a signal, and calling pcap_breakloop() in the signal handler, you must specify, when catching those signals, that system calls should NOT be restarted by that signal. Otherwise, if the signal interrupted a call reading packets in a live capture, when your signal handler returns after calling pcap_breakloop(), the call will be restarted, and the loop will not terminate until more packets arrive and the call completes.

这可能是您观察到的。及时收到警报信号,但您未能指定不应通过该信号重新启动系统调用。因此,pcap_loop() 不会立即返回。

参见 How to know if a Linux system call is restartable or not?

关于c++ - alarm() 在随机时间后生成 SIGALRM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53316536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com