10
A
回答
10
您可以使用ncurses,或者如果你不想,你就可以按照本blog post描述的使用選擇。基本上,您可以使用select
並指定超時。如果stdin FD被設置,那麼你可以安全地讀取它,並且不會阻塞。如果你想在選擇更多的信息,請檢查this了,當然還有wikipedia。知道這是一個方便的電話。
編輯:我覺得不得不提供代碼,所以在這裏,直接從博客文章發表一些評論。調用read()
前
// if != 0, then there is data to be read on stdin
int kbhit()
{
// timeout structure passed into select
struct timeval tv;
// fd_set passed into select
fd_set fds;
// Set up the timeout. here we can wait for 1 second
tv.tv_sec = 1;
tv.tv_usec = 0;
// Zero out the fd_set - make sure it's pristine
FD_ZERO(&fds);
// Set the FD that we want to read
FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0
// select takes the last file descriptor value + 1 in the fdset to check,
// the fdset for reads, writes, and errors. We are only passing in reads.
// the last parameter is the timeout. select will return if an FD is ready or
// the timeout has occurred
select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
// return 0 if STDIN is not ready to be read.
return FD_ISSET(STDIN_FILENO, &fds);
}
0
呼叫alarm()
或ualarm()
。這將導致SIGALRM
信號被傳送到進程,中斷read(),提供的你沒有告訴O/S在中斷後重新啓動系統調用。如果read()
正常返回,請務必取消報警。
+1
'SIGALRM'的默認吊掛器會終止這個過程,所以您需要安裝一個信號處理器。在一個理智的操作系統中,默認情況下,信號不會中斷系統調用,所以您需要使用'sigaction'而不是'signal'來確保它們。 – 2010-09-15 00:29:48
6
使用select,poll或任何其他IO複用工具。他們都採取超時的說法。 請注意,如果stdin是普通文件,這將不起作用,但如果stdin是終端/ tty,套接字,管道,則它將不起作用。
例如
fd_set selectset;
struct timeval timeout = {10,0}; //timeout of 10 secs.
int ret;
FD_ZERO(&selectset);
FD_SET(0,&selectset);
ret = select(1,&selectset,NULL,NULL,&timeout);
if(ret == 0)
//timeout
else if(ret == -1)
//error
else
// stdin has data, read it
// (we know stdin is readable, since we only asked for read events
//and stdin is the only fd in our select set.
相關問題
- 1. 閱讀()從標準輸入讀取流
- 2. 輸入設置超時(cin)
- 3. 閱讀標準輸入中的Spyder
- 4. 同時閱讀stdin並在python中寫入標準輸出
- 5. 閱讀從標準輸入中golang
- 6. 設置超時設置的套接字有時會在閱讀時失速
- 7. 用戶輸入設置超時
- 8. 閱讀時間
- 9. 如何閱讀child_process.spawnSync標準輸出與標準輸入輸出選項 '繼承'
- 10. HttpURLConnection的閱讀超時
- 11. 如何閱讀和檢查在Python中的標準輸入/標準輸出?
- 12. 寫入到標準輸入並從標準輸出中讀取長時間運行的子進程中的python
- 13. 如何設置Socket.ConnectAsync的超時時間?
- 14. 設置java.net.URLConnection的最大超時時間
- 15. 如何設置OCILogon2的超時時間?
- 16. 在XP上閱讀Windows事件時間超過1小時,閱讀Vista的時間是正確的
- 17. Ruby和Redis:爲訂閱設置超時
- 18. C#與閱讀標準輸出問題
- 19. 從標準輸入讀取
- 20. tokuDb設置時間以超時語句
- 21. 爲NetworkObject.MapNetworkDrive設置超時時間
- 22. 基於查詢設置超時時間
- 23. Libtorrent如何設置超時時間?
- 24. 動態設置超時時間
- 25. iOS:Firebase存儲設置超時時間
- 26. 閱讀輸入時遇到問題
- 27. 寫入標準輸出並從標準輸入讀取C
- 28. 如何設置InputStream.read的讀取超時?
- 29. 讀取標準輸入用戶輸入一個文件時已經重定向到標準輸入
- 30. Python:同時使用標準輸入和標準輸出
+1好博文。 – Tom 2010-09-14 19:09:59