admin 管理员组

文章数量: 1086019


2024年1月23日发(作者:jspcmsx)

linux poll实例代码

以下是一个简单的示例代码,演示了如何在Linux中使用poll函数来监视多个文件描述符的I/O事件:

c.

#include

#include

#include

#include

int main() {。

struct pollfd fds[2];

int timeout_msecs = 5000; // 5 seconds.

int ret;

// 监视标准输入。

fds[0].fd = 0; // 标准输入。

fds[0].events = POLLIN;

// 监视标准输出。

fds[1].fd = 1; // 标准输出。

fds[1].events = POLLOUT;

// 使用poll函数进行监视。

ret = poll(fds, 2, timeout_msecs);

if (ret == -1) {。

perror("poll");

return 1;

}。

if (ret == 0) {。

printf("Poll timeout.n");

} else {。

if (fds[0].revents & POLLIN) {。

printf("Readable data on stdin.n");

}。

if (fds[1].revents & POLLOUT) {。

printf("Writable data on stdout.n");

}。

}。

return 0;

}。

在这个示例中,我们首先定义了两个文件描述符(标准输入和标准输出),然后使用poll函数来监视这两个文件描述符的I/O事件。我们设置了一个5秒的超时时间,并在超时或者事件发生时进行相应的处理。这个示例很简单,但演示了poll函数的基本用法。希望对你有所帮助。


本文标签: 监视 函数 标准 进行 文件