我正在閱讀有關C編程的投票,並在poll(2)手冊頁中構建了一個應用程序。
這裏是例子:
輪詢C Linux函數如何工作?
#include<stdio.h>
#include <stropts.h>
#include <poll.h>
#include <fcntl.h>
int main() {
struct pollfd fds[2];
int timeout_msecs = -1;
int ret;
int i;
/* Open STREAMS device. */
fds[0].fd = open("/home/jeshwanth/mywork/poll/dev0", O_RDONLY);
fds[1].fd = open("/home/jeshwanth/mywork/poll/dev1", O_RDONLY);
fds[0].events = POLLOUT | POLLWRBAND;
fds[1].events = POLLOUT | POLLWRBAND;
while (1) {
ret = poll(fds, 2, timeout_msecs);
if (ret > 0) {
/* An event on one of the fds has occurred. */
for (i = 0; i < 2; i++) {
if (fds[i].revents != 0) {
/* Priority data may be written on device number i. */
printf(
"Priority Data may be written on device number %d POLLWRBAND\n",
i);
}
if (fds[i].revents = !0) {
/* Data may be written on device number i. */
printf("Data may be written on device number %d POLLOUT\n",
i);
}
if (fds[i].revents = !0) {
/* A hangup has occurred on device number i. */
printf("A hangup has occurred on device number %d\n", i);
}
}
}
}
return 0;
}
注:裝置0和DEV1是正常的文件。當我運行程序時,如果在dev0和dev1中沒有發生事件,則顯示消息。但是我期待有人寫入文件時,只有它應該顯示消息。我錯了嗎?
沒有那些'printf'應爲每個封閉那些來執行'if'分支具備的條件'0'。 – oldrinb
@oldrinb謝謝,我在發佈之前測試它,所以我誤以爲=,現在它是!=。忘了那些printf的,怎麼ret> 0?如果文件沒有變化? –
你的代碼仍然是錯誤的,但現在它會打印後面的2條消息,因爲它們的封閉'if'分支都具有'!0'的條件。 – oldrinb