[英]How to “try” to read input in C
我正在編寫一個程序,該程序允許在Linux中的兩個進程之間進行聊天。 要傳輸消息,我使用IPC隊列。
我的主循環有問題:我需要檢查隊列中是否有任何新消息,以及是否有-打印它。 然后,我需要檢查是否有任何輸入,以及是否有-scanf(這是問題)。 有任何想法嗎?
使用非阻塞操作。 如果對使用O_NONBLOCK
標志打開的文件描述符執行read()
,並且此時沒有可用數據,則read()
將以errno = -EWOULDBLOCK
返回。
另一種選擇是使用select()
輪詢多個描述符。
為我的帖子增加更多價值,我正在粘貼一個發現的示例,它解決了我的問題
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
fd_set rfds;
struct timeval tv;
int retval;
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(1, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
if (retval == −1)
perror("select()");
else if (retval)
printf("Data is available now.\n");
/* FD_ISSET(0, &rfds) will be true. */
else
printf("No data within five seconds.\n");
exit(EXIT_SUCCESS);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.