![](/img/trans.png)
[英]is there a way to check if external data is piped to a program or if program runs on its own?
[英]How do I check if my program has data piped into it
我正在編寫一個應該通過stdin讀取輸入的程序,所以我有以下結構。
FILE *fp=stdin;
但是如果用戶沒有將任何東西輸入到程序中,這只會掛起,我如何檢查用戶是否實際將數據傳輸到我的程序中
gunzip -c file.gz |./a.out #should work
./a.out #should exit program with nice msg.
謝謝
由於您正在使用文件指針,因此您需要isatty()
和fileno()
來執行此操作:
#include <unistd.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
FILE* fp = stdin;
if(isatty(fileno(fp)))
{
fprintf(stderr, "A nice msg.\n");
exit(1);
}
/* carry on... */
return 0;
}
實際上,這是漫長的道路。 簡短的方法是不使用文件指針:
#include <unistd.h>
int main(int argc, char* argv[])
{
if(isatty(STDIN_FILENO))
{
fprintf(stderr, "A nice msg.\n");
exit(1);
}
/* carry on... */
return 0;
}
幾個標准的Unix程序會檢查它們以修改它們的行為。 例如,如果你設置了ls
來為你提供漂亮的顏色,那么如果將stdout傳遞給另一個程序,它將關閉顏色。
將stdin傳遞給select()或poll()應告訴您輸入是否在等待。 在許多操作系統下,您還可以判斷stdin是tty還是管道。
編輯:我看到我不得不強調TTY測試的也有一部分。 fifo不是tty,但可能沒有任何輸入准備好無限期的時間。
嘗試“man isatty”,我認為該功能會告訴您是否與用戶交談。
使用isatty
來檢測stdin是來自終端而不是重定向。
查看函數“isatty” - 如果STDIN是終端,則可以跳過讀取。 如果它不是終端,您將獲得數據管道或重定向,您可以閱讀直到EOF。
使用select()獲得的另一個選項是設置從stdin讀取的超時(相對於stdin的第一次讀取或stdin的連續讀取)。
有關在stdin上使用select的代碼示例,請參閱:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.