我在我的一个小项目上探索poll()函数,我注意到这个片段崩溃了:
ErrorCode XNotifier_Linux::updatePoll()
{
ErrorCode ret = Success;
struct pollfd descriptors = { m_fd, IN_MODIFY, 0 };
const int nbDescriptors = poll(&descriptors, m_fd+1, 10*1000);
if (descriptors.events & (POLLIN | POLLPRI))
ret = DataIsPresent;
return ret;
}
Run Code Online (Sandbox Code Playgroud)
Valgrind在这里非常有帮助,因为它指出了ufds
unitialized 中的poll字段:
==833== Syscall param poll(ufds.fd) points to uninitialised byte(s)
==833== at 0x569CB28: poll (in /lib64/libc-2.14.1.so)
==833== by 0x400F7A: xnot::XNotifier_Linux::updatePoll() (linux.cpp:72)
==833== by 0x400D4B: xnot::XNotifier_Linux::update() (linux.cpp:28)
==833== by 0x400FF4: main (linux.cpp:90)
==833== Address 0x7fefffbb8 is on thread 1's stack
Run Code Online (Sandbox Code Playgroud)
正如descriptors
在堆栈上创建的那样,我理解当函数返回时,指针descriptors
不再有效.我认为在函数返回后可能会使用此指针.为了确认这一点,我将声明描述符的行更改为:static struct pollfd descriptors = { m_fd, IN_MODIFY, 0 };
并且崩溃消失了.
为什么描述符应该比poll()的调用更长?(或者有什么我错了吗?)
P.-S. :描述符由inotify填充m_fd = inotify_init();
你误认了这个问题.
const int nbDescriptors = poll(&descriptors, m_fd+1, 10*1000);
Run Code Online (Sandbox Code Playgroud)
这是错误的,因为第一个参数poll
是(指向一个)数组,第二个参数是该数组中的元素数.
结果,系统调用正在读取数组的末尾.通过宣布它static
你只是在记忆中移动了东西并且很幸运.
你需要:
const int nbDescriptors = poll(&descriptors, 1, 10*1000);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
191 次 |
最近记录: |