[問題] 每秒檢查檔案

看板C_and_CPP作者時間7年前 (2016/12/02 21:57), 7年前編輯推噓5(5014)
留言19則, 8人參與, 最新討論串1/1
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) GCC 問題(Question): 我設計一個程式每秒去檢查某檔案是否存在 每10秒顯示目前經過秒數 預期的正確結果(Expected Output): 每秒顯示一次資訊 錯誤結果(Wrong Output): 10秒才一次性顯示全部資訊 程式碼(Code):(請善用置底文網頁, 記得排版) int main(){ FILE *fid_rd; int count=0,accu=0; while(1){ fid_rd=fopen(".running","r"); sleep(1); if(!fid_rd){ printf("finish\n"); break; }else{ printf("."); if(count==9){ count=0; accu+=10; printf("Simulator has took %d secs\n",accu); }else count++; fclose(fid_rd); } return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.214.129.158 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1480687047.A.6FF.html

12/02 22:24, , 1F
你需要的可能是fflush (亂猜)
12/02 22:24, 1F

12/02 22:38, , 2F
sleep(1)?
12/02 22:38, 2F

12/02 22:39, , 3F
sleep(999)還差不多
12/02 22:39, 3F

12/02 22:57, , 4F
printf("."); 後面加 fflush(stdin);
12/02 22:57, 4F

12/02 22:57, , 5F
printf("."); 後面加 fflush(stdin);
12/02 22:57, 5F

12/02 22:58, , 6F
還有你為什麼要先 sleep 再檢查 fopen 是否成功...
12/02 22:58, 6F

12/02 23:07, , 7F
沒有newline就要自己flush
12/02 23:07, 7F
※ 編輯: jacky1989 (49.214.130.241), 12/02/2016 23:13:26

12/02 23:30, , 8F
睡眠時間太短機器可能跟不上,這開檔。int..
12/02 23:30, 8F

12/02 23:38, , 9F
1是一毫秒喔 至少要800毫秒以上
12/02 23:38, 9F

12/03 00:13, , 10F
https://linux.die.net/man/3/sleep sleep應該是這個?
12/03 00:13, 10F

12/03 00:14, , 11F
https://goo.gl/CX1x2j 跟這個不一樣
12/03 00:14, 11F

12/03 00:22, , 12F
關鍵字:gcc file exists
12/03 00:22, 12F

12/03 00:43, , 13F
什麼 fflush(stdin)... 不要亂教
12/03 00:43, 13F

12/03 00:44, , 14F
對不起... 打錯字...
12/03 00:44, 14F

12/03 00:44, , 15F
這裡要 fflush 也是 fflush(stdout), 這個是可以用的
12/03 00:44, 15F
想請問為什麼需要fflush呢? ※ 編輯: jacky1989 (123.192.57.91), 12/03/2016 02:50:12 ※ 編輯: jacky1989 (123.192.57.91), 12/03/2016 02:52:03

12/03 08:25, , 16F
基本上是在猜測 printf 出來的東西因為被 buffer 住了
12/03 08:25, 16F

12/03 08:27, , 17F
所以在推出去到螢幕之前就 sleep 了導致東西一次印出來
12/03 08:27, 17F

12/03 08:27, , 18F
fflush(stdout); 就是在強迫這些 buffer 住的東西印出來
12/03 08:27, 18F

12/03 15:29, , 19F
因為stdout是line buffered
12/03 15:29, 19F
文章代碼(AID): #1OGNt7R_ (C_and_CPP)