我有一个简单的 C 程序,我在我的 Ubuntu 22.04 VM 上编译了它,它通过 VirtualBox 在我的 MacBook 上运行:
#include <poll.h>
#include <stdio.h>
#include <unistd.h>
int main() {
int fds[2];
struct pollfd poller = {.events = POLLIN};
if ( pipe(fds) != 0 ) {
perror("pipe");
return 1;
}
poller.fd = fds[0];
poll(&poller, 1, 1000);
close(fds[0]);
close(fds[1]);
return 0;
}
显然,
fds[0]
永远不会准备好读取,所以 poll
应该在 1000 毫秒后超时。
然而,当我跑步时
while true; do time ./a.out; done
我明白了
./a.out 0.01s user 0.00s system 0% cpu 9.924 total
./a.out 0.01s user 0.00s system 0% cpu 10.837 total
./a.out 0.01s user 0.01s system 0% cpu 4.070 total
./a.out 0.01s user 0.00s system 0% cpu 8.606 total
./a.out 0.00s user 0.00s system 0% cpu 1.131 total
./a.out 0.01s user 0.01s system 1% cpu 1.018 total
./a.out 0.00s user 0.01s system 0% cpu 2.682 total
./a.out 0.00s user 0.00s system 0% cpu 1.598 total
./a.out 0.01s user 0.00s system 1% cpu 1.018 total
./a.out 0.01s user 0.00s system 1% cpu 1.017 total
./a.out 0.01s user 0.00s system 1% cpu 1.055 total
./a.out 0.01s user 0.00s system 1% cpu 1.019 total
./a.out 0.01s user 0.01s system 1% cpu 1.045 total
./a.out 0.00s user 0.01s system 1% cpu 1.078 total
./a.out 0.00s user 0.01s system 0% cpu 8.336 total
./a.out 0.01s user 0.01s system 0% cpu 3.344 total
./a.out 0.01s user 0.00s system 1% cpu 1.019 total
./a.out 0.01s user 0.02s system 2% cpu 1.050 total
./a.out 0.00s user 0.01s system 1% cpu 1.022 total
./a.out 0.01s user 0.00s system 1% cpu 1.014 total
./a.out 0.00s user 0.00s system 0% cpu 2.352 total
./a.out 0.00s user 0.00s system 0% cpu 1.023 total
./a.out 0.01s user 0.00s system 0% cpu 1.323 total
...
在单独的终端中运行
htop
显示最小的 CPU/内存使用率(VM 有 4 个 2 GHz 处理器和 4 GB RAM)。
为什么
poll
会产生这种不一致的行为?