看板 Programming 關於我們 聯絡資訊
下午經友人提供訊息, 有一個 function 叫 setbuf, 可供測試 經過測試後, 發現真的是 buf 的影響, 將 buf 設成 NULL 就結果正常啦 XD 不曉得這算不算是驗證我上一篇的猜測 :P 順便把 code 貼上來 或許哪天會幫到別人吧 XD Usage> ./a.out 次數 是否setbuf為NULL ex: # ./a.out 100000 Y; 代表要跑 十萬 次且把 fd 的 buffer 設成 NULL 可以同時跑 3 支試試, 結果會存在 sum 這個檔案, 記得要先生一下 結果應該是 30 萬才對 # ./a.out 100000 N; 代表要跑 十萬 次但不把 fd 的 buffer 設成 NULL 可以同時跑 3 支試試, 結果應該不是 30 萬 XD 心得: 這東西的正常與否應該是跟 OS 的預設環境有關啦 :P 不過我也正在思考 setbuf( fd, NULL ) 對效能的影響了 == 以下程式, 看不懂得勿用, 不負責任何執行結果, 僅供參考 ( shell 有砍檔的動作啦 ) == 簡單的 shell script : == #!/bin/sh rm -rf sum; echo "0" > sum; # 砍掉 sum 這個檔案, 並建其內容為 0 gcc lock_test.c ; ./a.out 100000 Y & ./a.out 100000 Y & ./a.out 100000 Y & == lock_test.c == #include <stdio.h> #include <stdlib.h> #include <sys/file.h> void LockFileByPtr( FILE * fd ) { if( flock( fileno( fd ) , LOCK_EX ) != 0 ) { perror(" Error @ LockFilePtr "); exit(1); } } void UnlockFileByPtr( FILE * fd ) // 印象中直接 fclose 也行?!要查查 { if( flock( fileno( fd ) , LOCK_UN ) != 0 ) { perror(" Error @ UnlockFileByPtr "); exit(1); } fclose( fd ); } int main( int argc , char* argv[] ) { FILE *fd ; char buf[100] , set_buf_null; unsigned int x , i , count; if( argc != 3 ) return; count = atoi(argv[1]); set_buf_null = argv[2][0]; i = 0; while( i < count ){ fd = fopen( "sum" , "r+" ); if( set_buf_null == 'Y') setbuf( fd , NULL ); LockFileByPtr( fd ); // 接著對 "target" file 做更新 fgets( buf , 100 , fd ); x = atoi( buf ); x++; rewind(fd); fprintf( fd , "%u\n",x); // 更新完 unlock UnlockFileByPtr( fd ); i++; } return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.123.217.56
legnaleurc:不知道fsync來不來得及在有buffer的140.123.224.125 04/20 19:03
legnaleurc:狀況下同步?140.123.224.125 04/20 19:04